1import sys,json,os
2
3import docker
4import requests
5
6def start_image(client,name):
7   run= False
8   try:
9    client.images.pull(name)
10    image=client.images.get(name)
11    print('image found:',image.id)
12   except Exception:
13    print("downloading image ... ", name)
14    image=client.images.pull(name)
15    print('image downloaded:', image.id)
16   for container in client.containers.list(filters={"ancestor":name,"status":"running"}):
17         run=True
18   if not run:
19       id=client.containers.run(name,ports={1080:1080}, detach=True)
20       print(id)
21   else:
22       print("container is already running")
23
24def stop_containar(client,name):
25    for container in client.containers.list(filters={"ancestor":"jamesdbloom/mockserver:latest","status":"running"}):
26        container.stop()
27
28def setup():
29    url='http://localhost:1080/mockserver/expectation'
30    file = open('b/resources/eventing/curl_setup.txt')
31    data = json.load(file)
32    for d in data:
33        response = requests.put(url, data=json.dumps(d))
34        if response.status_code==201:
35            pass
36        else:
37            raise Exception('erro occured: ',response.text)
38    res=requests.put('http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS')
39    print(json.dumps(res.json(), indent=4, sort_keys=True))
40
41def reset():
42    url = 'http://localhost:1080/mockserver/reset'
43    response = requests.put(url)
44    if response.status_code == 200:
45        pass
46    else:
47        raise Exception('error occured: ', response.text)
48    res = requests.put('http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS')
49    print("Active api's:",json.dumps(res.json(), indent=4, sort_keys=True))
50
51
52if __name__ == "__main__":
53   client = docker.from_env()
54   operation = sys.argv[1]
55   if operation == 'start':
56    start_image(client,'jamesdbloom/mockserver:latest')
57   elif operation == 'stop':
58    stop_containar(client,'jamesdbloom/mockserver:latest')
59   elif operation == 'setup':
60       setup()
61   elif operation == 'reset':
62       reset()