internal.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package internal contains miscellaneous functions and types
  4. // that are internal to the syspolicy packages.
  5. package internal
  6. import (
  7. "bytes"
  8. "github.com/go-json-experiment/json/jsontext"
  9. "tailscale.com/types/lazy"
  10. "tailscale.com/util/testenv"
  11. "tailscale.com/version"
  12. )
  13. // Init facilitates deferred invocation of initializers.
  14. var Init lazy.DeferredInit
  15. // OSForTesting is the operating system override used for testing.
  16. // It follows the same naming convention as [version.OS].
  17. var OSForTesting lazy.SyncValue[string]
  18. // OS is like [version.OS], but supports a test hook.
  19. func OS() string {
  20. return OSForTesting.Get(version.OS)
  21. }
  22. // EqualJSONForTest compares the JSON in j1 and j2 for semantic equality.
  23. // It returns "", "", true if j1 and j2 are equal. Otherwise, it returns
  24. // indented versions of j1 and j2 and false.
  25. func EqualJSONForTest(tb testenv.TB, j1, j2 jsontext.Value) (s1, s2 string, equal bool) {
  26. tb.Helper()
  27. j1 = j1.Clone()
  28. j2 = j2.Clone()
  29. // Canonicalize JSON values for comparison.
  30. if err := j1.Canonicalize(); err != nil {
  31. tb.Error(err)
  32. }
  33. if err := j2.Canonicalize(); err != nil {
  34. tb.Error(err)
  35. }
  36. // Check and return true if the two values are structurally equal.
  37. if bytes.Equal(j1, j2) {
  38. return "", "", true
  39. }
  40. // Otherwise, format the values for display and return false.
  41. if err := j1.Indent(); err != nil {
  42. tb.Fatal(err)
  43. }
  44. if err := j2.Indent(); err != nil {
  45. tb.Fatal(err)
  46. }
  47. return j1.String(), j2.String(), false
  48. }