Skip to content

Commit 1b21ce5

Browse files
committed
making a pre-test service
1 parent c31ce59 commit 1b21ce5

File tree

1 file changed

+45
-14
lines changed

1 file changed

+45
-14
lines changed

cns/restserver/api_test.go

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -176,9 +176,10 @@ func TestMain(m *testing.M) {
176176
logger.InitLogger("testlogs", 0, 0, "./")
177177

178178
// Create the service. If CRD channel mode is needed, then at the start of the test,
179-
// it can stop the service (service.Stop), invoke startService again with new ServiceConfig (with CRD mode)
180-
// perform the test and then restore the service again.
181-
if err = startService(common.ServiceConfig{ChannelMode: cns.Direct}, configuration.CNSConfig{}); err != nil {
179+
// it can stop the service (via the returned stop func), invoke startService again with
180+
// new ServiceConfig (with CRD mode), perform the test and then restore the service again.
181+
stop, _, err := startService(common.ServiceConfig{ChannelMode: cns.Direct}, configuration.CNSConfig{})
182+
if err != nil {
182183
fmt.Printf("Failed to start CNS Service. Error: %v", err)
183184
os.Exit(1)
184185
}
@@ -207,7 +208,8 @@ func TestMain(m *testing.M) {
207208
exitCode := m.Run()
208209

209210
// Cleanup.
210-
service.Stop()
211+
// Use the stop func returned by startService to ensure proper teardown.
212+
stop()
211213
nmAgentServer.Stop()
212214

213215
os.Exit(exitCode)
@@ -1031,7 +1033,7 @@ func publishNCViaCNS(
10311033

10321034
if bodyStatus != expStatus {
10331035
// nolint:goerr113 // this is okay in a test:
1034-
return fmt.Errorf("unexpected status in body. exp: %d, got %d", expStatus, bodyStatus)
1036+
return fmt.Errorf("unexpected status in body. exp: %d, got: %d", expStatus, bodyStatus)
10351037
}
10361038
}
10371039

@@ -1787,23 +1789,23 @@ func setEnv(t *testing.T) *httptest.ResponseRecorder {
17871789
return w
17881790
}
17891791

1790-
func startService(serviceConfig common.ServiceConfig, _ configuration.CNSConfig) error {
1792+
func startService(serviceConfig common.ServiceConfig, _ configuration.CNSConfig) (func(), *HTTPRestService, error) {
17911793
// Create the service.
17921794
config := serviceConfig
17931795

17941796
// Create the key value fileStore.
17951797
fileStore, err := store.NewJsonFileStore(cnsJsonFileName, processlock.NewMockFileLock(false), nil)
17961798
if err != nil {
17971799
logger.Errorf("Failed to create store file: %s, due to error %v\n", cnsJsonFileName, err)
1798-
return err
1800+
return nil, nil, err
17991801
}
18001802
config.Store = fileStore
18011803

18021804
nmagentClient := &fakes.NMAgentClientFake{}
18031805
service, err = NewHTTPRestService(&config, &fakes.WireserverClientFake{}, &fakes.WireserverProxyFake{}, &IPtablesProvider{},
18041806
nmagentClient, nil, nil, nil, fakes.NewMockIMDSClient())
18051807
if err != nil {
1806-
return err
1808+
return nil, nil, err
18071809
}
18081810
svc = service.(*HTTPRestService)
18091811
svc.Service.Options[acncommon.OptCnsURL] = ""
@@ -1839,6 +1841,7 @@ func startService(serviceConfig common.ServiceConfig, _ configuration.CNSConfig)
18391841
return resp, nil
18401842
}
18411843

1844+
var perTestSvc *HTTPRestService
18421845
if service != nil {
18431846
// Create empty azure-cns.json. CNS should start successfully by deleting this file
18441847
file, _ := os.Create(cnsJsonFileName)
@@ -1850,25 +1853,43 @@ func startService(serviceConfig common.ServiceConfig, _ configuration.CNSConfig)
18501853
err = service.Init(&config)
18511854
if err != nil {
18521855
logger.Errorf("Failed to Init CNS, err:%v.\n", err)
1853-
return err
1856+
return nil, nil, err
18541857
}
18551858

18561859
err = service.Start(&config)
18571860
if err != nil {
18581861
logger.Errorf("Failed to start CNS, err:%v.\n", err)
1859-
return err
1862+
return nil, nil, err
18601863
}
18611864

18621865
if _, err := os.Stat(cnsJsonFileName); err == nil || !os.IsNotExist(err) {
18631866
logger.Errorf("Failed to remove empty CNS state file: %s, err:%v", cnsJsonFileName, err)
1864-
return err
1867+
return nil, nil, err
18651868
}
1869+
perTestSvc = service.(*HTTPRestService)
18661870
}
18671871

18681872
// Get the internal http mux as test hook.
1869-
mux = service.(*HTTPRestService).Listener.GetMux()
1873+
if perTestSvc == nil {
1874+
return nil, nil, fmt.Errorf("service was not created")
1875+
}
1876+
mux = perTestSvc.Listener.GetMux()
18701877

1871-
return nil
1878+
// stop func cleans up the running service and any test artifacts.
1879+
stop := func() {
1880+
if service != nil {
1881+
// ignore stop errors
1882+
service.Stop()
1883+
}
1884+
// best-effort remove temp file
1885+
_ = os.Remove(cnsJsonFileName)
1886+
// clear globals to avoid cross-test leakage
1887+
svc = nil
1888+
service = nil
1889+
mux = nil
1890+
}
1891+
1892+
return stop, perTestSvc, nil
18721893
}
18731894

18741895
func contains(networkContainers []cns.GetNetworkContainerResponse, str string) bool {
@@ -1918,8 +1939,18 @@ func TestGetVMUniqueIDFailed(t *testing.T) {
19181939
}
19191940

19201941
func TestIBDevices(t *testing.T) {
1942+
// If a particular test needs to run with an isolated ServiceConfig (different ChannelMode
1943+
// for example), startService now returns a stop func and the instantiated *HTTPRestService.
1944+
// Example per-test usage (uncomment to use):
1945+
stop, perTestSvc, err := startService(common.ServiceConfig{ChannelMode: cns.CRD}, configuration.CNSConfig{})
1946+
if err != nil {
1947+
t.Fatalf("failed to start per-test service: %v", err)
1948+
}
1949+
defer stop()
1950+
// You can then use 'perTestSvc' for test-local assertions and the returned stop func will
1951+
// cleanly tear down the service when the test finishes.
1952+
19211953
var (
1922-
err error
19231954
req *http.Request
19241955
ibDevicesReq cns.AssignIBDevicesToPodRequest
19251956
body bytes.Buffer

0 commit comments

Comments
 (0)