MCPcopy
hub / github.com/usememos/memos / GetMySQLDSN

Function GetMySQLDSN

store/test/containers.go:90–157  ·  view source on GitHub ↗

GetMySQLDSN starts a MySQL container (if not already running) and creates a fresh database for this test.

(t *testing.T)

Source from the content-addressed store, hash-verified

88
89// GetMySQLDSN starts a MySQL container (if not already running) and creates a fresh database for this test.
90func GetMySQLDSN(t *testing.T) string {
91 skipIfContainerProviderUnavailable(t)
92
93 ctx := context.Background()
94
95 mysqlOnce.Do(func() {
96 nw, err := requireTestNetwork(ctx)
97 if err != nil {
98 t.Fatalf("failed to create test network: %v", err)
99 }
100
101 container, err := mysql.Run(ctx,
102 "mysql:8",
103 mysql.WithDatabase("init_db"),
104 mysql.WithUsername("root"),
105 mysql.WithPassword(testPassword),
106 testcontainers.WithEnv(map[string]string{
107 "MYSQL_ROOT_PASSWORD": testPassword,
108 }),
109 testcontainers.WithWaitStrategy(
110 wait.ForAll(
111 wait.ForLog("ready for connections").WithOccurrence(2),
112 wait.ForListeningPort("3306/tcp"),
113 ).WithDeadline(120*time.Second),
114 ),
115 network.WithNetwork([]string{mysqlNetworkAlias}, nw),
116 )
117 if err != nil {
118 t.Fatalf("failed to start MySQL container: %v", err)
119 }
120 mysqlContainer.Store(container)
121
122 dsn, err := container.ConnectionString(ctx, "multiStatements=true")
123 if err != nil {
124 t.Fatalf("failed to get MySQL connection string: %v", err)
125 }
126
127 if err := waitForDB("mysql", dsn, 30*time.Second); err != nil {
128 t.Fatalf("MySQL not ready for connections: %v", err)
129 }
130
131 mysqlBaseDSN.Store(dsn)
132 })
133
134 dsn, ok := mysqlBaseDSN.Load().(string)
135 if !ok || dsn == "" {
136 t.Fatal("MySQL container failed to start in a previous test")
137 }
138
139 // Serialize database creation to avoid "table already exists" race conditions
140 dbCreationMutex.Lock()
141 defer dbCreationMutex.Unlock()
142
143 // Create a fresh database for this test
144 dbName := fmt.Sprintf("memos_test_%d", dbCounter.Add(1))
145 db, err := sql.Open("mysql", dsn)
146 if err != nil {
147 t.Fatalf("failed to connect to MySQL: %v", err)

Callers 2

Calls 5

requireTestNetworkFunction · 0.85
waitForDBFunction · 0.85
RunMethod · 0.65
CloseMethod · 0.65

Tested by 1