|
| 1 | +/* |
| 2 | +Copyright 2025 API Testing Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package cmd |
| 18 | + |
| 19 | +import ( |
| 20 | + "os" |
| 21 | + "os/signal" |
| 22 | + "syscall" |
| 23 | + |
| 24 | + "github.com/linuxsuren/api-testing/pkg/mock" |
| 25 | + "github.com/spf13/cobra" |
| 26 | +) |
| 27 | + |
| 28 | +func createMockComposeCmd() (c *cobra.Command) { |
| 29 | + c = &cobra.Command{ |
| 30 | + Use: "mock-compose", |
| 31 | + Short: "Mock multiple servers", |
| 32 | + Args: cobra.ExactArgs(1), |
| 33 | + RunE: func(cmd *cobra.Command, args []string) (err error) { |
| 34 | + reader := mock.NewLocalFileReader(args[0]) |
| 35 | + |
| 36 | + var server *mock.Server |
| 37 | + if server, err = reader.Parse(); err != nil { |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + var subServers []mock.DynamicServer |
| 42 | + for _, proxy := range server.Proxies { |
| 43 | + subProxy := &mock.Server{ |
| 44 | + Proxies: []mock.Proxy{proxy}, |
| 45 | + } |
| 46 | + |
| 47 | + subReader := mock.NewObjectReader(subProxy) |
| 48 | + subServer := mock.NewInMemoryServer(c.Context(), proxy.Port) |
| 49 | + if err = subServer.Start(subReader, proxy.Prefix); err != nil { |
| 50 | + return |
| 51 | + } |
| 52 | + subServers = append(subServers, subServer) |
| 53 | + } |
| 54 | + |
| 55 | + clean := make(chan os.Signal, 1) |
| 56 | + signal.Notify(clean, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT) |
| 57 | + select { |
| 58 | + case <-c.Context().Done(): |
| 59 | + case <-clean: |
| 60 | + } |
| 61 | + for _, server := range subServers { |
| 62 | + server.Stop() |
| 63 | + } |
| 64 | + return |
| 65 | + }, |
| 66 | + } |
| 67 | + return |
| 68 | +} |
0 commit comments