forked from inventree/inventree-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.py
195 lines (141 loc) · 5.22 KB
/
tasks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# -*- coding: utf-8 -*-
try:
from invoke import ctask as task
except ImportError:
from invoke import task
import os
import sys
import time
import requests
from requests.auth import HTTPBasicAuth
@task
def style(c):
"""
Run PEP style checks against the codebase
"""
print("Running PEP code style checks...")
c.run('flake8 .')
@task
def reset_data(c, debug=False):
"""
Reset the database to a known state.
This is achieved by installing the InvenTree test fixture data.
"""
# Reset the database to a known state
print("Reset test database to a known state (this might take a little while...)")
hide = None if debug else 'both'
c.run("docker-compose -f test/docker-compose.yml run inventree-py-test-server invoke delete-data -f", hide=hide)
c.run("docker-compose -f test/docker-compose.yml run inventree-py-test-server invoke migrate", hide=hide)
c.run("docker-compose -f test/docker-compose.yml run inventree-py-test-server invoke import-fixtures", hide=hide)
@task(post=[reset_data])
def update_image(c, debug=True, reset=True):
"""
Update the InvenTree image to the latest version
"""
print("Pulling latest InvenTree image from docker hub (maybe grab a coffee!)")
hide = None if debug else 'both'
c.run("docker-compose -f test/docker-compose.yml pull", hide=hide)
c.run("docker-compose -f test/docker-compose.yml run inventree-py-test-server invoke update", hide=hide)
if reset:
reset_data(c)
@task
def check_server(c, host="http://localhost:12345", username="testuser", password="testpassword", debug=True, timeout=30):
"""
Check that we can ping the server and get a token.
A generous timeout is applied here, to give the server time to activate
"""
auth = HTTPBasicAuth(username=username, password=password)
url = f"{host}/api/user/token/"
response = None
while response is None:
try:
response = requests.get(url, auth=auth, timeout=0.5)
except Exception as e:
if debug:
print("Error:", str(e))
if response is None:
if timeout > 0:
if debug:
print(f"No response from server. {timeout} seconds remaining")
timeout -= 1
time.sleep(1)
else:
return False
if response.status_code != 200:
if debug:
print(f"Invalid status code: ${response.status_code}")
return False
if 'token' not in response.text:
if debug:
print("Token not in returned response:")
print(str(response.text))
return False
# We have confirmed that the server is available
if debug:
print(f"InvenTree server is available at {host}")
return True
@task
def start_server(c, debug=False):
"""
Launch the InvenTree server (in a docker container)
"""
# Start the InvenTree server
print("Starting InvenTree server instance")
c.run('docker-compose -f test/docker-compose.yml up -d', hide=None if debug else 'both')
print("Waiting for InvenTree server to respond:")
count = 60
while not check_server(c, debug=False) and count > 0:
count -= 1
time.sleep(1)
if count == 0:
print("No response from InvenTree server")
sys.exit(1)
else:
print("InvenTree server is active!")
@task
def stop_server(c, debug=False):
"""
Stop a running InvenTree test server docker container
"""
# Stop the server
c.run('docker-compose -f test/docker-compose.yml down', hide=None if debug else 'both')
@task
def test(c, source=None, update=False, reset=False, debug=False):
"""
Run the unit tests for the python bindings.
Performs the following steps:
- Ensure the docker container is up and running
- Reset the database to a known state (if --reset flag is given)
- Perform unit testing
"""
# If a source file is provided, check that it actually exists
if source:
if not source.endswith('.py'):
source += '.py'
if not os.path.exists(source):
source = os.path.join('test', source)
if not os.path.exists(source):
print(f"Error: Source file '{source}' does not exist")
sys.exit(1)
if update:
# Pull down the latest InvenTree docker image
update_image(c, debug=debug)
if reset:
stop_server(c, debug=debug)
reset_data(c, debug=debug)
# Launch the InvenTree server (in a docker container)
start_server(c)
# Wait until the docker server is running, and API is accessible
# Set environment variables so test scripts can access them
os.environ['INVENTREE_PYTHON_TEST_SERVER'] = 'http://localhost:12345'
os.environ['INVENTREE_PYTHON_TEST_USERNAME'] = 'testuser'
os.environ['INVENTREE_PYTHON_TEST_PASSWORD'] = 'testpassword'
# Run unit tests
# If a single source file is supplied, test *just* that file
# Otherwise, test *all* files
if source:
print(f"Running tests for '{source}'")
c.run(f'coverage run -m unittest {source}')
else:
# Automatically discover tests, and run only those
c.run('coverage run -m unittest discover -s test/')