TestAuditableResources ensures that all auditable resources are included in the Auditable interface and vice versa. nolint:tparallel
(t *testing.T)
| 20 | // |
| 21 | //nolint:tparallel |
| 22 | func TestAuditableResources(t *testing.T) { |
| 23 | t.Parallel() |
| 24 | |
| 25 | pkgs, err := packages.Load(&packages.Config{ |
| 26 | Mode: packages.NeedTypes | packages.NeedDeps, |
| 27 | }, "../../coderd/audit") |
| 28 | require.NoError(t, err) |
| 29 | |
| 30 | if len(pkgs) != 1 { |
| 31 | t.Fatal("expected one package") |
| 32 | } |
| 33 | auditPkg := pkgs[0] |
| 34 | auditableType := auditPkg.Types.Scope().Lookup("Auditable") |
| 35 | |
| 36 | // If any of these type cast fails, our Auditable interface is not what we |
| 37 | // expect it to be. |
| 38 | named, ok := auditableType.(*types.TypeName) |
| 39 | require.True(t, ok, "expected Auditable to be a type name") |
| 40 | |
| 41 | interfaceType, ok := named.Type().(*types.Named).Underlying().(*types.Interface) |
| 42 | require.True(t, ok, "expected Auditable to be an interface") |
| 43 | |
| 44 | unionType, ok := interfaceType.EmbeddedType(0).(*types.Union) |
| 45 | require.True(t, ok, "expected Auditable to be a union") |
| 46 | |
| 47 | found := make(map[string]bool) |
| 48 | expectedList := make([]string, 0) |
| 49 | // Now we check we have all the resources in the AuditableResources |
| 50 | for i := 0; i < unionType.Len(); i++ { |
| 51 | // All types come across like 'github.com/coder/coder/v2/coderd/database.<type>' |
| 52 | typeName := unionType.Term(i).Type().String() |
| 53 | _, ok := AuditableResources[typeName] |
| 54 | assert.True(t, ok, "missing resource %q from AuditableResources", typeName) |
| 55 | found[typeName] = true |
| 56 | expectedList = append(expectedList, typeName) |
| 57 | } |
| 58 | |
| 59 | // Also check that all resources in the table are in the union. We could |
| 60 | // have extra resources here. |
| 61 | for name := range AuditableResources { |
| 62 | _, ok := found[name] |
| 63 | assert.True(t, ok, "extra resource %q found in AuditableResources", name) |
| 64 | } |
| 65 | |
| 66 | // Various functions that have switch statements to include all Auditable |
| 67 | // resources. Make sure we have all types supported. |
| 68 | // nolint:paralleltest |
| 69 | t.Run("ResourceID", func(t *testing.T) { |
| 70 | // The function being tested, provided here to make it easier to find |
| 71 | _ = audit.ResourceID[database.APIKey] |
| 72 | testAuditFunctionWithSwitch(t, auditPkg, "ResourceID", expectedList) |
| 73 | }) |
| 74 | |
| 75 | // nolint:paralleltest |
| 76 | t.Run("ResourceType", func(t *testing.T) { |
| 77 | // The function being tested, provided here to make it easier to find |
| 78 | _ = audit.ResourceType[database.APIKey] |
| 79 | testAuditFunctionWithSwitch(t, auditPkg, "ResourceType", expectedList) |