| 22 | } |
| 23 | |
| 24 | func TestNewDB_PingError(t *testing.T) { |
| 25 | // Store original URI to restore later |
| 26 | originalURI := os.Getenv("PD_MONGO_URI") |
| 27 | defer os.Setenv("PD_MONGO_URI", originalURI) |
| 28 | |
| 29 | testLogger := logger.GetLogger() |
| 30 | |
| 31 | t.Run("ping_fails_with_invalid_host", func(t *testing.T) { |
| 32 | // Try with a completely invalid host that will fail on ping |
| 33 | os.Setenv("PD_MONGO_URI", "mongodb://nonexistent-host-12345:27017") |
| 34 | |
| 35 | testCfg := cfg.GetCfg() |
| 36 | |
| 37 | db, err := NewDB(testCfg, testLogger) |
| 38 | |
| 39 | // This should fail either on connect or ping |
| 40 | assert.Error(t, err) |
| 41 | assert.Nil(t, db) |
| 42 | }) |
| 43 | |
| 44 | t.Run("ping_fails_with_unreachable_port", func(t *testing.T) { |
| 45 | // Use a port that's likely not running MongoDB |
| 46 | os.Setenv("PD_MONGO_URI", "mongodb://localhost:12345") |
| 47 | |
| 48 | testCfg := cfg.GetCfg() |
| 49 | |
| 50 | db, err := NewDB(testCfg, testLogger) |
| 51 | |
| 52 | // This should fail on connection or ping |
| 53 | assert.Error(t, err) |
| 54 | assert.Nil(t, db) |
| 55 | }) |
| 56 | |
| 57 | t.Run("ping_fails_with_short_timeout", func(t *testing.T) { |
| 58 | // Use a very short timeout that will likely cause ping to fail |
| 59 | os.Setenv("PD_MONGO_URI", "mongodb://localhost:27017/?serverSelectionTimeoutMS=1&connectTimeoutMS=1") |
| 60 | |
| 61 | testCfg := cfg.GetCfg() |
| 62 | |
| 63 | db, err := NewDB(testCfg, testLogger) |
| 64 | |
| 65 | // This should fail on connection or ping due to timeout |
| 66 | assert.Error(t, err) |
| 67 | assert.Nil(t, db) |
| 68 | }) |
| 69 | } |