forked from inventree/inventree-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
290 lines (206 loc) · 8.44 KB
/
test_api.py
File metadata and controls
290 lines (206 loc) · 8.44 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# -*- coding: utf-8 -*-
import os
import sys
import unittest
import requests
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from inventree import api # noqa: E402
from inventree import base # noqa: E402
from inventree import part # noqa: E402
from inventree import stock # noqa: E402
SERVER = os.environ.get('INVENTREE_PYTHON_TEST_SERVER', 'http://127.0.0.1:12345')
USERNAME = os.environ.get('INVENTREE_PYTHON_TEST_USERNAME', 'testuser')
PASSWORD = os.environ.get('INVENTREE_PYTHON_TEST_PASSWORD', 'testpassword')
class URLTests(unittest.TestCase):
"""Class for testing URL functionality"""
def test_base_url(self):
"""Test validation of URL provided to InvenTreeAPI class"""
# Each of these URLs should be invalid
for url in [
"test.com/123",
"http://:80/123",
"//xyz.co.uk",
]:
with self.assertRaises(Exception):
a = api.InvenTreeAPI(url, connect=False)
# test for base URL construction
a = api.InvenTreeAPI('https://test.com', connect=False)
self.assertEqual(a.base_url, 'https://test.com/')
self.assertEqual(a.api_url, 'https://test.com/api/')
# more tests that the base URL is set correctly under specific conditions
urls = [
"http://a.b.co:80/sub/dir/api/",
"http://a.b.co:80/sub/dir/api",
"http://a.b.co:80/sub/dir/",
"http://a.b.co:80/sub/dir",
]
for url in urls:
a = api.InvenTreeAPI(url, connect=False)
self.assertEqual(a.base_url, "http://a.b.co:80/sub/dir/")
self.assertEqual(a.api_url, "http://a.b.co:80/sub/dir/api/")
def test_url_construction(self):
"""Test that the API class correctly constructs URLs"""
a = api.InvenTreeAPI("http://localhost:1234", connect=False)
tests = {
'part/': 'http://localhost:1234/api/part/',
'/api/stock/': 'http://localhost:1234/api/stock/',
'/plugin/part/': 'http://localhost:1234/plugin/part/',
'order/so/shipment': 'http://localhost:1234/api/order/so/shipment',
'https://example.com/': 'https://example.com/',
}
for endpoint, url in tests.items():
self.assertEqual(a.constructApiUrl(endpoint), url)
class LoginTests(unittest.TestCase):
def test_failed_logins(self):
# Attempt connection where no server exists
with self.assertRaises(Exception):
a = api.InvenTreeAPI("http://127.0.0.1:9999", username="admin", password="password")
# Attempt connection with invalid credentials
with self.assertRaises(Exception):
a = api.InvenTreeAPI(SERVER, username="abcde", password="********")
self.assertIsNotNone(a.server_details)
self.assertIsNone(a.token)
class Unauthenticated(unittest.TestCase):
"""
Test that we cannot access the data if we are not authenticated.
"""
def setUp(self):
self.api = api.InvenTreeAPI(SERVER, username="hello", password="world", connect=False)
def test_read_parts(self):
with self.assertRaises(Exception) as ar:
part.Part.list(self.api)
self.assertIn('Authentication at InvenTree server failed', str(ar.exception))
def test_file_download(self):
"""
Attempting to download a file while unauthenticated should raise an error
"""
# Downloading without auth = unauthorized error (401)
with self.assertRaises(requests.exceptions.HTTPError):
self.assertFalse(self.api.downloadFile('/media/part/files/1/test.pdf', 'test.pdf'))
class Timeout(unittest.TestCase):
"""
Test that short timeout leads to correct error
"""
def test_timeout(self):
"""
This unrealistically short timeout should lead to a timeout error
"""
# Attempt connection with short timeout
with self.assertRaises(requests.exceptions.ReadTimeout):
a = api.InvenTreeAPI(SERVER, username=USERNAME, password=PASSWORD, timeout=0.001) # noqa: F841
class InvenTreeTestCase(unittest.TestCase):
"""
Base class for running InvenTree unit tests.
- Creates an authenticated API instance
"""
def setUp(self):
"""
Test case setup functions
"""
self.api = api.InvenTreeAPI(
SERVER,
username=USERNAME, password=PASSWORD,
timeout=30,
token_name='python-test',
use_token_auth=True
)
class InvenTreeAPITest(InvenTreeTestCase):
def test_token(self):
self.assertIsNotNone(self.api.token)
def test_details(self):
self.assertIsNotNone(self.api.server_details)
details = self.api.server_details
self.assertIn('server', details)
self.assertIn('instance', details)
self.assertIn('apiVersion', details)
api_version = int(details['apiVersion'])
self.assertTrue(api_version >= self.api.getMinApiVersion())
class TestCreate(InvenTreeTestCase):
"""
Test that objects can be created via the API
"""
def test_create_stuff(self):
with self.assertRaises(requests.exceptions.ReadTimeout):
# Test short timeout for a specific function
c = part.PartCategory.create(self.api, {
'parent': None,
'name': 'My custom category',
'description': 'A part category',
}, timeout=0.001)
n = part.PartCategory.count(self.api)
# Create a custom category
c = part.PartCategory.create(self.api, {
'parent': None,
'name': f'Custom category {n + 1}',
'description': 'A part category',
})
self.assertIsNotNone(c)
self.assertIsNotNone(c.pk)
n = part.Part.count(self.api)
p = part.Part.create(self.api, {
'name': f'ACME Widget {n}',
'description': 'A simple widget created via the API',
'category': c.pk,
'ipn': f'ACME-0001-{n}',
'virtual': False,
'active': True
})
self.assertIsNotNone(p)
self.assertEqual(p.category, c.pk)
cat = p.getCategory()
self.assertEqual(cat.pk, c.pk)
s = stock.StockItem.create(self.api, {
'part': p.pk,
'quantity': 45,
'notes': 'This is a note',
})[0]
self.assertIsNotNone(s)
self.assertEqual(s.part, p.pk)
prt = s.getPart()
self.assertEqual(prt.pk, p.pk)
self.assertEqual(prt.name, f'ACME Widget {n}')
class TemplateTest(InvenTreeTestCase):
def test_get_widget(self):
widget = part.Part(self.api, 10000)
self.assertEqual(widget.name, "Chair Template")
test_templates = widget.getTestTemplates()
self.assertGreaterEqual(len(test_templates), 5)
keys = [test.key for test in test_templates]
self.assertIn('teststrengthofchair', keys)
self.assertIn('applypaint', keys)
self.assertIn('attachlegs', keys)
def test_add_template(self):
"""
Test that we can add a test template via the API
"""
widget = part.Part(self.api, pk=10000)
n = len(widget.getTestTemplates())
part.PartTestTemplate.create(self.api, {
'part': widget.pk,
'test_name': f"Test_Name_{n}",
'description': 'A test or something',
'required': True,
})
self.assertEqual(len(widget.getTestTemplates()), n + 1)
def test_add_result(self):
# Look for a particular serial number
items = stock.StockItem.list(self.api, serial=1000)
self.assertEqual(len(items), 1)
item = items[0]
tests = item.getTestResults()
n = len(tests)
# Upload a test result against 'firmware' (should fail the first time)
args = {
'attachment': 'test/attachment.txt',
'value': '0x123456',
}
result = item.uploadTestResult('firmwareversion', False, **args)
self.assertTrue(result)
item.uploadTestResult('temperaturetest', True)
item.uploadTestResult('settingschecksum', False, value='some data')
# There should be 3 more test results now!
results = item.getTestResults()
self.assertEqual(len(results), n + 3)
if __name__ == '__main__':
print("Running InvenTree Python Unit Tests: Version " + base.INVENTREE_PYTHON_VERSION)
unittest.main()