Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CI: Add pre-commit hook to use modern testing asserts #7126

Merged
merged 3 commits into from
Apr 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,7 @@ repos:
# rev: 3.0.0
# hooks:
# - id: shellcheck
- repo: https://github.com/isidentical/teyit
rev: 0.4.3
hooks:
- id: teyit
2 changes: 1 addition & 1 deletion src/backend/InvenTree/InvenTree/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def test_role_view(self):
response = self.client.get(url, format='json')

# Not logged in, so cannot access user role data
self.assertTrue(response.status_code in [401, 403])
self.assertIn(response.status_code, [401, 403])

# Now log in!
self.basicAuth()
Expand Down
12 changes: 6 additions & 6 deletions src/backend/InvenTree/InvenTree/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,7 @@ def test_tuple(self):

s = '.'.join([str(i) for i in v])

self.assertTrue(s in version.inventreeVersion())
self.assertIn(s, version.inventreeVersion())

def test_comparison(self):
"""Test direct comparison of version numbers."""
Expand All @@ -1039,10 +1039,10 @@ def test_comparison(self):
v_c = version.inventreeVersionTuple('1.2.4')
v_d = version.inventreeVersionTuple('2.0.0')

self.assertTrue(v_b > v_a)
self.assertTrue(v_c > v_b)
self.assertTrue(v_d > v_c)
self.assertTrue(v_d > v_a)
self.assertGreater(v_b, v_a)
self.assertGreater(v_c, v_b)
self.assertGreater(v_d, v_c)
self.assertGreater(v_d, v_a)

def test_commit_info(self):
"""Test that the git commit information is extracted successfully."""
Expand Down Expand Up @@ -1505,7 +1505,7 @@ def test_generation(self):
self.assertEqual(mail.outbox[0].subject, '[InvenTree] Log in to the app')

# Check that the token is in the email
self.assertTrue('http://testserver/api/email/login/' in mail.outbox[0].body)
self.assertIn('http://testserver/api/email/login/', mail.outbox[0].body)
token = mail.outbox[0].body.split('/')[-1].split('\n')[0][8:]
self.assertEqual(get_user(token), self.user)

Expand Down
2 changes: 1 addition & 1 deletion src/backend/InvenTree/InvenTree/unit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ def process_csv(
):
"""Helper function to process and validate a downloaded csv file."""
# Check that the correct object type has been passed
self.assertTrue(isinstance(file_object, io.StringIO))
self.assertIsInstance(file_object, io.StringIO)

file_object.seek(0)

Expand Down
4 changes: 2 additions & 2 deletions src/backend/InvenTree/build/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def test_complete(self):
expected_code=400
)

self.assertTrue('accept_unallocated' in response.data)
self.assertIn('accept_unallocated', response.data)

# Accept unallocated stock
self.post(
Expand Down Expand Up @@ -934,7 +934,7 @@ def test_overallocated_requires_acceptance(self):
{},
expected_code=400
)
self.assertTrue('accept_overallocated' in response.data)
self.assertIn('accept_overallocated', response.data)

# Check stock items have not reduced at all
for si, oq, _ in self.state.values():
Expand Down
6 changes: 3 additions & 3 deletions src/backend/InvenTree/common/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_settings_objects(self):
# There should be two settings objects in the database
settings = InvenTreeSetting.objects.all()

self.assertTrue(settings.count() >= 2)
self.assertGreaterEqual(settings.count(), 2)

instance_name = InvenTreeSetting.objects.get(pk=1)
self.assertEqual(instance_name.key, 'INVENTREE_INSTANCE')
Expand Down Expand Up @@ -207,7 +207,7 @@ def run_settings_check(self, key, setting):
- Ensure that every setting key is valid
- Ensure that a validator is supplied
"""
self.assertTrue(type(setting) is dict)
self.assertIs(type(setting), dict)

name = setting.get('name', None)

Expand Down Expand Up @@ -726,7 +726,7 @@ def test_scheduled_tasks(self):
response = self.get(url, expected_code=200)

for task in response.data:
self.assertTrue(task['name'] == 'time.sleep')
self.assertEqual(task['name'], 'time.sleep')


class WebhookMessageTests(TestCase):
Expand Down
2 changes: 1 addition & 1 deletion src/backend/InvenTree/company/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def test_company_create(self):
expected_code=400,
)

self.assertTrue('currency' in response.data)
self.assertIn('currency', response.data)

def test_company_active(self):
"""Test that the 'active' value and filter works."""
Expand Down
6 changes: 3 additions & 3 deletions src/backend/InvenTree/label/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,18 @@ def test_default_labels(self):
"""Test that the default label templates are copied across."""
labels = StockItemLabel.objects.all()

self.assertTrue(labels.count() > 0)
self.assertGreater(labels.count(), 0)

labels = StockLocationLabel.objects.all()

self.assertTrue(labels.count() > 0)
self.assertGreater(labels.count(), 0)

def test_default_files(self):
"""Test that label files exist in the MEDIA directory."""

def test_subdir(ref_name):
item_dir = settings.MEDIA_ROOT.joinpath('label', 'inventree', ref_name)
self.assertTrue(len([item_dir.iterdir()]) > 0)
self.assertGreater(len([item_dir.iterdir()]), 0)

test_subdir('stockitem')
test_subdir('stocklocation')
Expand Down
71 changes: 41 additions & 30 deletions src/backend/InvenTree/machine/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,18 @@ def test_machine_type_list(self):
machine_type = [t for t in response.data if t['slug'] == 'label-printer']
self.assertEqual(len(machine_type), 1)
machine_type = machine_type[0]
self.assertDictContainsSubset(
self.assertEqual(
machine_type,
{
'slug': 'label-printer',
'name': 'Label Printer',
'description': 'Directly print labels for various items.',
'provider_plugin': None,
'is_builtin': True,
**machine_type,
**{
'slug': 'label-printer',
'name': 'Label Printer',
'description': 'Directly print labels for various items.',
'provider_plugin': None,
'is_builtin': True,
},
},
machine_type,
)
self.assertTrue(
machine_type['provider_file'].endswith(
Expand All @@ -102,17 +105,20 @@ def test_machine_driver_list(self):
driver = [a for a in response.data if a['slug'] == 'test-label-printer-api']
self.assertEqual(len(driver), 1)
driver = driver[0]
self.assertDictContainsSubset(
self.assertEqual(
driver,
{
'slug': 'test-label-printer-api',
'name': 'Test label printer',
'description': 'This is a test label printer driver for testing.',
'provider_plugin': None,
'is_builtin': True,
'machine_type': 'label-printer',
'driver_errors': [],
**driver,
**{
'slug': 'test-label-printer-api',
'name': 'Test label printer',
'description': 'This is a test label printer driver for testing.',
'provider_plugin': None,
'is_builtin': True,
'machine_type': 'label-printer',
'driver_errors': [],
},
},
driver,
)
self.assertEqual(driver['provider_file'], __file__)

Expand Down Expand Up @@ -163,19 +169,22 @@ def test_machine_list(self):

response = self.get(reverse('api-machine-list'))
self.assertEqual(len(response.data), 1)
self.assertDictContainsSubset(
self.assertEqual(
response.data[0],
{
'name': 'Test Machine',
'machine_type': 'label-printer',
'driver': 'test-label-printer-api',
'initialized': True,
'active': True,
'status': 101,
'status_model': 'LabelPrinterStatus',
'status_text': '',
'is_driver_available': True,
**response.data[0],
**{
'name': 'Test Machine',
'machine_type': 'label-printer',
'driver': 'test-label-printer-api',
'initialized': True,
'active': True,
'status': 101,
'status_model': 'LabelPrinterStatus',
'status_text': '',
'is_driver_available': True,
},
},
response.data[0],
)

def test_machine_detail(self):
Expand All @@ -195,19 +204,21 @@ def test_machine_detail(self):

# Create a machine
response = self.post(reverse('api-machine-list'), machine_data)
self.assertDictContainsSubset(machine_data, response.data)
self.assertEqual(response.data, {**response.data, **machine_data})
pk = response.data['pk']

# Retrieve the machine
response = self.get(reverse('api-machine-detail', kwargs={'pk': pk}))
self.assertDictContainsSubset(machine_data, response.data)
self.assertEqual(response.data, {**response.data, **machine_data})

# Update the machine
response = self.patch(
reverse('api-machine-detail', kwargs={'pk': pk}),
{'name': 'Updated Machine'},
)
self.assertDictContainsSubset({'name': 'Updated Machine'}, response.data)
self.assertEqual(
response.data, {**response.data, **{'name': 'Updated Machine'}}
)
self.assertEqual(MachineConfig.objects.get(pk=pk).name, 'Updated Machine')

# Delete the machine
Expand Down
8 changes: 4 additions & 4 deletions src/backend/InvenTree/order/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def test_po_duplicate(self):

po = models.PurchaseOrder.objects.get(pk=1)

self.assertTrue(po.lines.count() > 0)
self.assertGreater(po.lines.count(), 0)

lines = []

Expand Down Expand Up @@ -839,7 +839,7 @@ def test_download_line_items(self):
expected_code=200,
expected_fn='InvenTree_PurchaseOrderItems.xlsx',
) as file:
self.assertTrue(isinstance(file, io.BytesIO))
self.assertIsInstance(file, io.BytesIO)


class PurchaseOrderReceiveTest(OrderTest):
Expand Down Expand Up @@ -1570,7 +1570,7 @@ def test_download_xls(self):
expected_fn='InvenTree_SalesOrders.xls',
decode=False,
) as file:
self.assertTrue(isinstance(file, io.BytesIO))
self.assertIsInstance(file, io.BytesIO)

def test_download_csv(self):
"""Test that the list of sales orders can be downloaded as a .csv file."""
Expand Down Expand Up @@ -1772,7 +1772,7 @@ def check_template(line_item):
# At least one item should be allocated, and all should be variants
self.assertGreater(self.order.stock_allocations.count(), 0)
for allocation in self.order.stock_allocations.all():
self.assertNotEquals(allocation.item.part.pk, allocation.line.part.pk)
self.assertNotEqual(allocation.item.part.pk, allocation.line.part.pk)

def test_shipment_complete(self):
"""Test that we can complete a shipment via the API."""
Expand Down
24 changes: 12 additions & 12 deletions src/backend/InvenTree/part/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,12 +463,12 @@ def test_path_detail(self):
response = self.get(url, {'path_detail': False}, expected_code=200)

# Check that the path detail information is not included
self.assertFalse('path' in response.data.keys())
self.assertNotIn('path', response.data.keys())

# Now, request *with* path detail
response = self.get(url, {'path_detail': True}, expected_code=200)

self.assertTrue('path' in response.data.keys())
self.assertIn('path', response.data.keys())

path = response.data['path']

Expand Down Expand Up @@ -520,7 +520,7 @@ def test_part(self):

# Check that a bunch o' fields are contained
for f in ['assembly', 'component', 'description', 'image', 'IPN']:
self.assertTrue(f in actions.keys())
self.assertIn(f, actions.keys())

# Active is a 'boolean' field
active = actions['active']
Expand Down Expand Up @@ -553,7 +553,7 @@ def test_category(self):
actions = self.getActions(reverse('api-part-category-list'))

# actions should *not* contain 'POST' as we do not have the correct role
self.assertFalse('POST' in actions)
self.assertNotIn('POST', actions)

self.assignRole('part_category.add')

Expand Down Expand Up @@ -1055,8 +1055,8 @@ def test_date_filters(self):
# Filter by creation date
response = self.get(url, {'created_before': '2019-01-01'}, expected_code=200)

self.assertTrue(len(response.data) < n)
self.assertTrue(len(response.data) > 0)
self.assertLess(len(response.data), n)
self.assertGreater(len(response.data), 0)

for item in response.data:
self.assertIsNotNone(item['creation_date'])
Expand All @@ -1066,8 +1066,8 @@ def test_date_filters(self):

response = self.get(url, {'created_after': '2019-01-01'}, expected_code=200)

self.assertTrue(len(response.data) < n)
self.assertTrue(len(response.data) > 0)
self.assertLess(len(response.data), n)
self.assertGreater(len(response.data), 0)

for item in response.data:
self.assertIsNotNone(item['creation_date'])
Expand Down Expand Up @@ -2153,7 +2153,7 @@ def test_bom_list(self):
response = self.get(url, data={'validated': False}, expected_code=200)

# There should be at least one non-validated item
self.assertTrue(len(response.data) > 0)
self.assertGreater(len(response.data), 0)

# Now, let's validate an item
bom_item = BomItem.objects.first()
Expand All @@ -2169,7 +2169,7 @@ def test_bom_list(self):
# Each item in response should contain expected keys
for el in response.data:
for key in ['available_stock', 'available_substitute_stock']:
self.assertTrue(key in el)
self.assertIn(key, el)

def test_bom_list_search(self):
"""Test that we can search the BOM list API endpoint."""
Expand Down Expand Up @@ -2208,7 +2208,7 @@ def test_bom_list_ordering(self):
q1 = response.data[0]['quantity']
q2 = response.data[-1]['quantity']

self.assertTrue(q1 < q2)
self.assertLess(q1, q2)

# Order by decreasing quantity
response = self.get(f'{url}?ordering=-quantity', expected_code=200)
Expand Down Expand Up @@ -2255,7 +2255,7 @@ def test_get_bom_detail(self):
]

for key in expected_values:
self.assertTrue(key in response.data)
self.assertIn(key, response.data)

self.assertEqual(int(float(response.data['quantity'])), 25)

Expand Down
4 changes: 2 additions & 2 deletions src/backend/InvenTree/part/test_category.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def test_path_string(self):
child.pathstring,
'Cat/AAAAAAAAAA/BBBBBBBBBB/CCCCCCCCCC/DDDDDDDDDD/EEEEEEEEEE/FFFFFFFFFF/GGGGGGGGGG/HHHHHHHHHH/IIIIIIIIII/JJJJJJJJJJ/KKKKKKKKK...OO/PPPPPPPPPP/QQQQQQQQQQ/RRRRRRRRRR/SSSSSSSSSS/TTTTTTTTTT/UUUUUUUUUU/VVVVVVVVVV/WWWWWWWWWW/XXXXXXXXXX/YYYYYYYYYY/ZZZZZZZZZZ',
)
self.assertTrue(len(child.pathstring) <= 250)
self.assertLessEqual(len(child.pathstring), 250)

# Attempt an invalid move
with self.assertRaises(ValidationError):
Expand Down Expand Up @@ -325,7 +325,7 @@ def test_category_tree(self):
self.assertEqual(descendants.count(), 3)

for loc in [C11, C12, C13]:
self.assertTrue(loc in descendants)
self.assertIn(loc, descendants)

# Check category C1x, should be B1 -> C1x
for loc in [C11, C12, C13]:
Expand Down
Loading
Loading