2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-04-29 12:06:44 +00:00

Tests: remove dead paths in test files (#6965)

* remove dead paths

* disable cov on fix for flaky tests

* remove dead path

* remove coverage from faliover path

* style fixes

* remove unused path

* cleanup

* ignore failure state for coverage

* reduce function complexity

* style fix

* more style fixes

* Revert "remove dead paths"

This reverts commit e6618d1925d003a548c06b7200dc211f6cba5d67.

* improve error message
This commit is contained in:
Matthias Mair 2024-04-05 22:33:52 +01:00 committed by GitHub
parent afa6586e10
commit 6bff55d620
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 32 additions and 51 deletions

View File

@ -1148,12 +1148,8 @@ class TestSettings(InvenTreeTestCase):
superuser = True superuser = True
def in_env_context(self, envs=None): def in_env_context(self, envs):
"""Patch the env to include the given dict.""" """Patch the env to include the given dict."""
# Set default - see B006
if envs is None:
envs = {}
return mock.patch.dict(os.environ, envs) return mock.patch.dict(os.environ, envs)
def run_reload(self, envs=None): def run_reload(self, envs=None):
@ -1588,15 +1584,15 @@ class ClassValidationMixinTest(TestCase):
def test(self): def test(self):
"""Test function.""" """Test function."""
pass ...
def test1(self): def test1(self):
"""Test function.""" """Test function."""
pass ...
def test2(self): def test2(self):
"""Test function.""" """Test function."""
pass ...
required_attributes = ['NAME'] required_attributes = ['NAME']
required_overrides = [test, [test1, test2]] required_overrides = [test, [test1, test2]]
@ -1616,11 +1612,11 @@ class ClassValidationMixinTest(TestCase):
def test(self): def test(self):
"""Test function.""" """Test function."""
pass ...
def test2(self): def test2(self):
"""Test function.""" """Test function."""
pass ...
TestClass.validate() TestClass.validate()
@ -1643,7 +1639,7 @@ class ClassValidationMixinTest(TestCase):
def test2(self): def test2(self):
"""Test function.""" """Test function."""
pass ...
with self.assertRaisesRegex( with self.assertRaisesRegex(
NotImplementedError, NotImplementedError,

View File

@ -157,12 +157,14 @@ class UserMixin:
if type(assign_all) is not bool: if type(assign_all) is not bool:
# Raise exception if common mistake is made! # Raise exception if common mistake is made!
raise TypeError('assignRole: assign_all must be a boolean value') raise TypeError(
'assignRole: assign_all must be a boolean value'
) # pragma: no cover
if not role and not assign_all: if not role and not assign_all:
raise ValueError( raise ValueError(
'assignRole: either role must be provided, or assign_all must be set' 'assignRole: either role must be provided, or assign_all must be set'
) ) # pragma: no cover
if not assign_all and role: if not assign_all and role:
rule, perm = role.split('.') rule, perm = role.split('.')
@ -241,14 +243,18 @@ class InvenTreeAPITestCase(ExchangeRateMixin, UserMixin, APITestCase):
yield # your test will be run here yield # your test will be run here
if verbose: if verbose:
msg = '\r\n%s' % json.dumps(context.captured_queries, indent=4) msg = '\r\n%s' % json.dumps(
context.captured_queries, indent=4
) # pragma: no cover
else: else:
msg = None msg = None
n = len(context.captured_queries) n = len(context.captured_queries)
if debug: if debug:
print(f'Expected less than {value} queries, got {n} queries') print(
f'Expected less than {value} queries, got {n} queries'
) # pragma: no cover
self.assertLess(n, value, msg=msg) self.assertLess(n, value, msg=msg)
@ -258,7 +264,7 @@ class InvenTreeAPITestCase(ExchangeRateMixin, UserMixin, APITestCase):
if expected_code is None: if expected_code is None:
return return
if expected_code != response.status_code: if expected_code != response.status_code: # pragma: no cover
print( print(
f"Unexpected {method} response at '{url}': status_code = {response.status_code}" f"Unexpected {method} response at '{url}': status_code = {response.status_code}"
) )
@ -280,11 +286,7 @@ class InvenTreeAPITestCase(ExchangeRateMixin, UserMixin, APITestCase):
response = self.client.options(url) response = self.client.options(url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
actions = response.data.get('actions', None) actions = response.data.get('actions', {})
if not actions:
actions = {}
return actions return actions
def get(self, url, data=None, expected_code=200, format='json', **kwargs): def get(self, url, data=None, expected_code=200, format='json', **kwargs):

View File

@ -46,7 +46,7 @@ class NewsFeedTests(TestCase):
"""Tests that news feed is updated when accessing a valid URL.""" """Tests that news feed is updated when accessing a valid URL."""
try: try:
common_tasks.update_news_feed() common_tasks.update_news_feed()
except Exception as ex: except Exception as ex: # pragma: no cover
self.fail(f'News feed raised exceptions: {ex}') self.fail(f'News feed raised exceptions: {ex}')
self.assertNotEqual(NewsFeedEntry.objects.all().count(), 0) self.assertNotEqual(NewsFeedEntry.objects.all().count(), 0)

View File

@ -1048,18 +1048,18 @@ class ColorThemeTest(TestCase):
"""Test that default choices are returned.""" """Test that default choices are returned."""
result = ColorTheme.get_color_themes_choices() result = ColorTheme.get_color_themes_choices()
# skip # skip due to directories not being set up
if not result: if not result:
return return # pragma: no cover
self.assertIn(('default', 'Default'), result) self.assertIn(('default', 'Default'), result)
def test_valid_choice(self): def test_valid_choice(self):
"""Check that is_valid_choice works correctly.""" """Check that is_valid_choice works correctly."""
result = ColorTheme.get_color_themes_choices() result = ColorTheme.get_color_themes_choices()
# skip # skip due to directories not being set up
if not result: if not result:
return return # pragma: no cover
# check wrong reference # check wrong reference
self.assertFalse(ColorTheme.is_valid_choice('abcdd')) self.assertFalse(ColorTheme.is_valid_choice('abcdd'))
@ -1099,10 +1099,12 @@ class CurrencyAPITests(InvenTreeAPITestCase):
# Exit early # Exit early
return return
# Delay and try again # Delay and try again - might have problems with exchange rate endpoint
time.sleep(10) time.sleep(10) # pragma: no cover
raise TimeoutError('Could not refresh currency exchange data after 5 attempts') raise TimeoutError(
'Could not refresh currency exchange data after 5 attempts'
) # pragma: no cover
class NotesImageTest(InvenTreeAPITestCase): class NotesImageTest(InvenTreeAPITestCase):

View File

@ -6,10 +6,8 @@ from .transition import StateTransitionMixin, TransitionMethod, storage
# Global variables to determine which transition classes raises an exception # Global variables to determine which transition classes raises an exception
global raise_storage global raise_storage
global raise_function
raise_storage = False raise_storage = False
raise_function = False
class MyPrivateError(NotImplementedError): class MyPrivateError(NotImplementedError):
@ -44,10 +42,8 @@ class TransitionTests(InvenTreeTestCase):
def test_storage(self): def test_storage(self):
"""Ensure that the storage collection mechanism works.""" """Ensure that the storage collection mechanism works."""
global raise_storage global raise_storage
global raise_function
raise_storage = True raise_storage = True
raise_function = False
class RaisingImplementation(TransitionMethod): class RaisingImplementation(TransitionMethod):
def transition(self, *args, **kwargs): def transition(self, *args, **kwargs):
@ -73,10 +69,8 @@ class TransitionTests(InvenTreeTestCase):
def test_function(self): def test_function(self):
"""Ensure that a TransitionMethod's function is called.""" """Ensure that a TransitionMethod's function is called."""
global raise_storage global raise_storage
global raise_function
raise_storage = False raise_storage = False
raise_function = True
# Setup # Setup
class ValidImplementationNoEffect(TransitionMethod): class ValidImplementationNoEffect(TransitionMethod):
@ -85,12 +79,7 @@ class TransitionTests(InvenTreeTestCase):
class ValidImplementation(TransitionMethod): class ValidImplementation(TransitionMethod):
def transition(self, *args, **kwargs): def transition(self, *args, **kwargs):
global raise_function
if raise_function:
return 1234 return 1234
else:
return False
storage.collect() storage.collect()
self.assertIn(ValidImplementationNoEffect, storage.list) self.assertIn(ValidImplementationNoEffect, storage.list)

View File

@ -23,7 +23,7 @@ class GeneralStatus(StatusCode):
def GHI(self): # This should be ignored def GHI(self): # This should be ignored
"""A invalid function.""" """A invalid function."""
pass ...
class GeneralStateTest(InvenTreeTestCase): class GeneralStateTest(InvenTreeTestCase):

View File

@ -64,11 +64,6 @@ class LabelTest(InvenTreeAPITestCase):
response = self.get(url, {'enabled': False}) response = self.get(url, {'enabled': False})
self.assertEqual(len(response.data), 0) self.assertEqual(len(response.data), 0)
# Disable each report
for label in labels:
label.enabled = False
label.save()
# Filter by "enabled" status # Filter by "enabled" status
response = self.get(url, {'enabled': True}) response = self.get(url, {'enabled': True})
self.assertEqual(len(response.data), 0) self.assertEqual(len(response.data), 0)

View File

@ -143,7 +143,7 @@ class MachineAPITest(TestMachineRegistryMixin, InvenTreeAPITestCase):
for error in errors_msgs: for error in errors_msgs:
if re.match(pattern, error): if re.match(pattern, error):
break break
else: else: # pragma: no cover
errors_str = '\n'.join([f'- {e}' for e in errors_msgs]) errors_str = '\n'.join([f'- {e}' for e in errors_msgs])
self.fail( self.fail(
f"""Error message matching pattern '{pattern}' not found in machine registry errors:\n{errors_str}""" f"""Error message matching pattern '{pattern}' not found in machine registry errors:\n{errors_str}"""

View File

@ -554,9 +554,6 @@ class StockItemListTest(StockAPITestCase):
) )
self.assertTrue(len(response.data) < StockItem.objects.count()) self.assertTrue(len(response.data) < StockItem.objects.count())
for result in response.data:
self.assertIsNone(result['location'])
# Filter with "cascade=True" # Filter with "cascade=True"
response = self.get( response = self.get(
self.list_url, {'location': 'null', 'cascade': True}, expected_code=200 self.list_url, {'location': 'null', 'cascade': True}, expected_code=200