|
| 1 | +package databasefake_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "reflect" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/coder/coder/coderd/database" |
| 9 | + |
| 10 | + "github.com/coder/coder/coderd/database/databasefake" |
| 11 | +) |
| 12 | + |
| 13 | +// TestExactMethods will ensure the fake database does not hold onto excessive |
| 14 | +// functions. The fake database is a manual implementation, so it is possible |
| 15 | +// we forget to delete functions that we remove. This unit test just ensures |
| 16 | +// we remove the extra methods. |
| 17 | +func TestExactMethods(t *testing.T) { |
| 18 | + // extraFakeMethods contains the extra allowed methods that are not a part |
| 19 | + // of the database.Store interface. |
| 20 | + extraFakeMethods := map[string]string{ |
| 21 | + // Example |
| 22 | + // "SortFakeLists": "Helper function used", |
| 23 | + } |
| 24 | + |
| 25 | + fake := reflect.TypeOf(databasefake.New()) |
| 26 | + fakeMethods := methods(fake) |
| 27 | + |
| 28 | + store := reflect.TypeOf((*database.Store)(nil)).Elem() |
| 29 | + storeMethods := methods(store) |
| 30 | + |
| 31 | + // Store should be a subset |
| 32 | + for k := range storeMethods { |
| 33 | + _, ok := fakeMethods[k] |
| 34 | + if !ok { |
| 35 | + panic(fmt.Sprintf("This should never happen. FakeDB missing method %s, so doesn't fit the interface", k)) |
| 36 | + } |
| 37 | + delete(storeMethods, k) |
| 38 | + delete(fakeMethods, k) |
| 39 | + } |
| 40 | + |
| 41 | + for k := range fakeMethods { |
| 42 | + _, ok := extraFakeMethods[k] |
| 43 | + if ok { |
| 44 | + continue |
| 45 | + } |
| 46 | + // If you are seeing this error, you have an extra function not required |
| 47 | + // for the database.Store. If you still want to keep it, add it to |
| 48 | + // 'extraFakeMethods' to allow it. |
| 49 | + t.Errorf("Fake method '%s()' is excessive and not needed to fit interface, delete it", k) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +func methods(rt reflect.Type) map[string]bool { |
| 54 | + methods := make(map[string]bool) |
| 55 | + for i := 0; i < rt.NumMethod(); i++ { |
| 56 | + methods[rt.Method(i).Name] = true |
| 57 | + } |
| 58 | + return methods |
| 59 | +} |
0 commit comments