|
5 | 5 | "testing" |
6 | 6 | "time" |
7 | 7 |
|
| 8 | + "github.com/pashagolub/pgxmock/v4" |
8 | 9 | "github.com/stretchr/testify/assert" |
9 | 10 |
|
10 | 11 | "github.com/cybertec-postgresql/pgwatch/v3/internal/sources" |
@@ -114,3 +115,57 @@ func TestMonitoredDatabase_IsPostgresSource(t *testing.T) { |
114 | 115 | md.Kind = sources.SourcePatroni |
115 | 116 | assert.True(t, md.IsPostgresSource(), "IsPostgresSource() = false, want true") |
116 | 117 | } |
| 118 | + |
| 119 | +type testSourceReader struct { |
| 120 | + sources.Sources |
| 121 | + error |
| 122 | +} |
| 123 | + |
| 124 | +func (r testSourceReader) GetSources() (sources.Sources, error) { |
| 125 | + return r.Sources, r.error |
| 126 | +} |
| 127 | + |
| 128 | +func TestMonitoredDatabases_SyncFromReader_error(t *testing.T) { |
| 129 | + reader := testSourceReader{error: assert.AnError} |
| 130 | + mds := sources.MonitoredDatabases{} |
| 131 | + _, err := mds.SyncFromReader(reader) |
| 132 | + assert.Error(t, err) |
| 133 | +} |
| 134 | + |
| 135 | +func TestMonitoredDatabases_SyncFromReader(t *testing.T) { |
| 136 | + db, _ := pgxmock.NewPool() |
| 137 | + src := sources.Source{ |
| 138 | + Name: "test", |
| 139 | + Kind: sources.SourcePostgres, |
| 140 | + IsEnabled: true, |
| 141 | + ConnStr: "postgres://user:password@localhost:5432/mydatabase", |
| 142 | + } |
| 143 | + reader := testSourceReader{Sources: sources.Sources{src}} |
| 144 | + // first read the sources |
| 145 | + mds, _ := reader.GetSources() |
| 146 | + assert.NotNil(t, mds, "GetSources() = nil, want not nil") |
| 147 | + // then resolve the databases |
| 148 | + mdbs, _ := mds.ResolveDatabases() |
| 149 | + assert.NotNil(t, mdbs, "ResolveDatabases() = nil, want not nil") |
| 150 | + // pretend that we have a connection |
| 151 | + mdbs[0].Conn = db |
| 152 | + db.ExpectClose() |
| 153 | + // sync the databases and make sure they are the same |
| 154 | + newmdbs, _ := mdbs.SyncFromReader(reader) |
| 155 | + assert.NotNil(t, newmdbs) |
| 156 | + assert.Equal(t, mdbs[0].ConnStr, newmdbs[0].ConnStr) |
| 157 | + assert.Equal(t, db, newmdbs[0].Conn) |
| 158 | + // change the connection string and check if databases are updated |
| 159 | + reader.Sources[0].ConnStr = "postgres://user:password@localhost:5432/anotherdatabase" |
| 160 | + newmdbs, _ = mdbs.SyncFromReader(reader) |
| 161 | + assert.NotNil(t, newmdbs) |
| 162 | + assert.NotEqual(t, mdbs[0].ConnStr, newmdbs[0].ConnStr) |
| 163 | + assert.Nil(t, newmdbs[0].Conn) |
| 164 | + assert.NoError(t, db.ExpectationsWereMet()) |
| 165 | + // change the unique name of the source and check if it's updated |
| 166 | + reader.Sources[0].Name = "another" |
| 167 | + newmdbs, _ = mdbs.SyncFromReader(reader) |
| 168 | + assert.NotNil(t, newmdbs) |
| 169 | + assert.NotEqual(t, mdbs[0].Name, newmdbs[0].Name) |
| 170 | + assert.Nil(t, newmdbs[0].Conn) |
| 171 | +} |
0 commit comments