code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_create_regex(self):
"""Test function for creating a regex from a format string."""
tests = {
'PO-123-{ref:04f}': r'^PO\-123\-(?P<ref>.+)$',
'{PO}-???-{ref}-{date}-22': r'^(?P<PO>.+)\-...\-(?P<ref>.+)\-(?P<date>.+)\-22$',
'ABC-123-###-{ref}': r'^ABC\-123\-\d\d... | Test function for creating a regex from a format string. | test_create_regex | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_validate_format(self):
"""Test that string validation works as expected."""
# These tests should pass
for value, pattern in {
'ABC-hello-123': '???-{q}-###',
'BO-1234': 'BO-{ref}',
'111.222.fred.china': '???.###.{name}.{place}',
'PO-1234':... | Test that string validation works as expected. | test_validate_format | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_extract_value(self):
"""Test that we can extract named values based on a format string."""
# Simple tests based on a straight-forward format string
fmt = 'PO-###-{ref:04d}'
tests = {'123': 'PO-123-123', '456': 'PO-123-456', '789': 'PO-123-789'}
for k, v in tests.items(... | Test that we can extract named values based on a format string. | test_extract_value | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_absolute_url(self):
"""Test helper function for generating an absolute URL."""
base = InvenTreeSetting.get_setting('INVENTREE_BASE_URL')
tests = {
'': base,
'api/': base + '/api/',
'/api/': base + '/api/',
'api': base + '/api',
... | Test helper function for generating an absolute URL. | test_absolute_url | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_image_url(self):
"""Test if a filename looks like an image."""
for name in ['ape.png', 'bat.GiF', 'apple.WeBP', 'BiTMap.Bmp']:
self.assertTrue(helpers.TestIfImageURL(name))
for name in ['no.doc', 'nah.pdf', 'whatpng']:
self.assertFalse(helpers.TestIfImageURL(nam... | Test if a filename looks like an image. | test_image_url | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_download_image(self):
"""Test function for downloading image from remote URL."""
# Run check with a sequence of bad URLs
for url in ['blog', 'htp://test.com/?', 'google', '\\invalid-url']:
with self.assertRaises(django_exceptions.ValidationError):
InvenTree.h... | Test function for downloading image from remote URL. | test_download_image | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_to_local_time(self):
"""Test that the local time conversion works as expected."""
source_time = timezone.datetime(
year=2000,
month=1,
day=1,
hour=0,
minute=1,
second=0,
tzinfo=ZoneInfo('Europe/London'),
... | Test that the local time conversion works as expected. | test_to_local_time | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_self_as_parent(self):
"""Test that we cannot set self as parent."""
loc = StockLocation.objects.get(pk=4)
loc.parent = loc
with self.assertRaises(ValidationError):
loc.save() | Test that we cannot set self as parent. | test_self_as_parent | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_child_as_parent(self):
"""Test that we cannot set a child as parent."""
parent = StockLocation.objects.get(pk=4)
child = StockLocation.objects.get(pk=5)
parent.parent = child
with self.assertRaises(ValidationError):
parent.save() | Test that we cannot set a child as parent. | test_child_as_parent | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_move(self):
"""Move an item to a different tree."""
drawer = StockLocation.objects.get(name='Drawer_1')
# Record the tree ID
tree = drawer.tree_id
home = StockLocation.objects.get(name='Home')
drawer.parent = home
drawer.save()
self.assertNotE... | Move an item to a different tree. | test_move | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_comparison(self):
"""Test direct comparison of version numbers."""
v_a = version.inventreeVersionTuple('1.2.0')
v_b = version.inventreeVersionTuple('1.2.3')
v_c = version.inventreeVersionTuple('1.2.4')
v_d = version.inventreeVersionTuple('2.0.0')
self.assertGrea... | Test direct comparison of version numbers. | test_comparison | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_set_user_to_few(self):
"""Test adding an admin user via env variables."""
user_model = get_user_model()
# add shortcut
user_count = user_model.objects.count
# enable testing mode
settings.TESTING_ENV = True
# nothing set
self.run_reload()
... | Test adding an admin user via env variables. | test_set_user_to_few | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_initial_install(self):
"""Test if install of plugins on startup works."""
from plugin import registry
registry.reload_plugins(full_reload=True, collect=True)
self.assertGreater(len(settings.PLUGIN_FILE_HASH), 0) | Test if install of plugins on startup works. | test_initial_install | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_offload_tasks(self):
"""Test that we can offload various tasks to the background worker thread.
This set of tests also ensures that various types of objects
can be encoded by the django-q serialization layer!
Note that as the background worker is not actually running for the t... | Test that we can offload various tasks to the background worker thread.
This set of tests also ensures that various types of objects
can be encoded by the django-q serialization layer!
Note that as the background worker is not actually running for the tests,
the call to 'offload_task' ... | test_offload_tasks | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_daily_holdoff(self):
"""Tests for daily task holdoff helper functions."""
import InvenTree.tasks
with self.assertLogs(logger='inventree', level='INFO') as cm:
# With a non-positive interval, task will not run
result = InvenTree.tasks.check_daily_holdoff('some_ta... | Tests for daily task holdoff helper functions. | test_daily_holdoff | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_barcode_model_type(self):
"""Test that the barcode_model_type property works for each class."""
from part.models import Part
from stock.models import StockItem, StockLocation
self.assertEqual(Part.barcode_model_type(), 'part')
self.assertEqual(StockItem.barcode_model_ty... | Test that the barcode_model_type property works for each class. | test_barcode_model_type | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_barcode_hash(self):
"""Test that the barcode hashing function provides correct results."""
# Test multiple values for the hashing function
# This is to ensure that the hash function is always "backwards compatible"
hashing_tests = {
'abcdefg': '7ac66c0f148de9519b8bd2... | Test that the barcode hashing function provides correct results. | test_barcode_hash | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_svg_sanitizer(self):
"""Test that SVGs are sanitized accordingly."""
valid_string = """<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="svg2" height="400" width="400">{0}
<path id="path1" d="m -151.78571,359.62883 v 112.76373 l 97.068507,-56.04253 V 303.14815 Z" style="fill:#dd... | Test that SVGs are sanitized accordingly. | test_svg_sanitizer | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_generation(self):
"""Test that magic login tokens are generated correctly."""
# User does not exists
resp = self.client.post(reverse('sesame-generate'), {'email': 1})
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.data, {'status': 'ok'})
self.asser... | Test that magic login tokens are generated correctly. | test_generation | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_timestamp(self):
"""Test that the timestamp value is interpreted correctly."""
KEY = '_MAINTENANCE_MODE'
# Deleting the setting means maintenance mode is off
InvenTreeSetting.objects.filter(key=KEY).delete()
self.assertFalse(get_maintenance_mode())
def set_tim... | Test that the timestamp value is interpreted correctly. | test_timestamp | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_valid_class(self):
"""Test that a valid class passes the validation."""
class TestClass(self.BaseTestClass):
"""A valid class that inherits from BaseTestClass."""
NAME = 'Test'
def test(self):
"""Test function."""
def test2(sel... | Test that a valid class passes the validation. | test_valid_class | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_invalid_class(self):
"""Test that an invalid class fails the validation."""
class TestClass1(self.BaseTestClass):
"""A bad class that inherits from BaseTestClass."""
with self.assertRaisesRegex(
NotImplementedError,
r'\'<.*TestClass1\'>\' did not pr... | Test that an invalid class fails the validation. | test_invalid_class | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def create_result_structure(self):
"""Create a schema dict structure representative of the spectacular-generated on."""
return {
'openapi': {},
'info': {},
'paths': {},
'components': {
'examples': {},
'parameters': {},
... | Create a schema dict structure representative of the spectacular-generated on. | create_result_structure | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_postprocess_required_nullable(self):
"""Verify that only selected elements are removed from required list."""
result_in = self.create_result_structure()
schemas_in = result_in.get('components').get('schemas')
schemas_in['SalesOrder'] = {
'properties': {
... | Verify that only selected elements are removed from required list. | test_postprocess_required_nullable | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tests.py | MIT |
def test_part_api(self):
"""Test that part list is working."""
url = reverse('api-part-list')
# Check JSON response
response = self.client.get(url, headers={'accept': 'application/json'})
self.assertEqual(response.status_code, 200) | Test that part list is working. | test_part_api | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_build_api(self):
"""Test that build list is working."""
url = reverse('api-build-list')
# Check JSON response
response = self.client.get(url, headers={'accept': 'application/json'})
self.assertEqual(response.status_code, 200) | Test that build list is working. | test_build_api | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_stock_api(self):
"""Test that stock list is working."""
url = reverse('api-stock-list')
# Check JSON response
response = self.client.get(url, headers={'accept': 'application/json'})
self.assertEqual(response.status_code, 200) | Test that stock list is working. | test_stock_api | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_company_list(self):
"""Test that company list is working."""
url = reverse('api-company-list')
# Check JSON response
response = self.client.get(url, headers={'accept': 'application/json'})
self.assertEqual(response.status_code, 200) | Test that company list is working. | test_company_list | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_not_found(self):
"""Test that the NotFoundView is working with all available methods."""
methods = ['options', 'get', 'post', 'patch', 'put', 'delete']
for method in methods:
response = getattr(self.client, method)('/api/anc')
self.assertEqual(response.status_cod... | Test that the NotFoundView is working with all available methods. | test_not_found | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def basicAuth(self):
"""Helper function to use basic auth."""
# Use basic authentication
authstring = bytes(f'{self.username}:{self.password}', 'ascii')
# Use "basic" auth by default
auth = b64encode(authstring).decode('ascii')
self.client.credentials(HTTP_AUTHORIZATION... | Helper function to use basic auth. | basicAuth | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def tokenAuth(self):
"""Helper function to use token auth."""
self.basicAuth()
token_url = reverse('api-token')
response = self.client.get(token_url, format='json', data={})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('token', response.data)
... | Helper function to use token auth. | tokenAuth | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_token_failure(self):
"""Test token resolve endpoint does not work without basic auth."""
# Test token endpoint without basic auth
url = reverse('api-token')
self.get(url, expected_code=401)
self.assertIsNone(self.token) | Test token resolve endpoint does not work without basic auth. | test_token_failure | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_role_view(self):
"""Test that we can access the 'roles' view for the logged in user.
Also tests that it is *not* accessible if the client is not logged in.
"""
url = reverse('api-user-roles')
# Delete all rules
self.group.rule_sets.all().delete()
update... | Test that we can access the 'roles' view for the logged in user.
Also tests that it is *not* accessible if the client is not logged in.
| test_role_view | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_with_superuser(self):
"""Superuser should have *all* roles assigned."""
self.user.is_superuser = True
self.user.save()
self.basicAuth()
response = self.get(reverse('api-user-roles'))
roles = response.data['roles']
for rule in RULESET_NAMES:
... | Superuser should have *all* roles assigned. | test_with_superuser | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_with_roles(self):
"""Assign some roles to the user."""
self.basicAuth()
url = reverse('api-user-roles')
response = self.get(url)
self.assignRole('part.delete')
self.assignRole('build.change')
response = self.get(url)
roles = response.data['ro... | Assign some roles to the user. | test_with_roles | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_list_endpoint_actions(self):
"""Tests for the OPTIONS method for API endpoints."""
self.basicAuth()
# Without any 'part' permissions, we should not see any available actions
url = reverse('api-part-list')
actions = self.getActions(url)
# Even without permissio... | Tests for the OPTIONS method for API endpoints. | test_list_endpoint_actions | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_detail_endpoint_actions(self):
"""Tests for detail API endpoint actions."""
self.basicAuth()
url = reverse('api-part-detail', kwargs={'pk': 1})
actions = self.getActions(url)
# No actions, as we do not have any permissions!
self.assertEqual(len(actions), 1)
... | Tests for detail API endpoint actions. | test_detail_endpoint_actions | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_errors(self):
"""Test that the correct errors are thrown."""
url = reverse('api-stock-test-result-list')
# DELETE without any of the required fields
response = self.delete(url, {}, expected_code=400)
self.assertIn(
'List of items or filters must be provided... | Test that the correct errors are thrown. | test_errors | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_search_filters(self):
"""Test that the regex, whole word, and notes filters are handled correctly."""
SEARCH_TERM = 'some note'
RE_SEARCH_TERM = 'some (.*) note'
response = self.post(
reverse('api-search'),
{'search': SEARCH_TERM, 'limit': 10, 'part': {}... | Test that the regex, whole word, and notes filters are handled correctly. | test_search_filters | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_permissions(self):
"""Test that users with insufficient permissions are handled correctly."""
# First, remove all roles
for ruleset in self.group.rule_sets.all():
ruleset.can_view = False
ruleset.can_change = False
ruleset.can_delete = False
... | Test that users with insufficient permissions are handled correctly. | test_permissions | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_api_version(self):
"""Test that the API text is correct."""
url = reverse('api-version-text')
response = self.get(url, format='json')
data = response.json()
self.assertEqual(len(data), 10)
response = self.get(reverse('api-version')).json()
self.assertIn... | Test that the API text is correct. | test_api_version | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_inventree_api_text_fnc(self):
"""Test that the inventreeApiText function works expected."""
latest_version = f'v{INVENTREE_API_VERSION}'
# Normal run
resp = inventreeApiText()
self.assertEqual(len(resp), 10)
self.assertIn(latest_version, resp)
# More re... | Test that the inventreeApiText function works expected. | test_inventree_api_text_fnc | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_parse_version_text_fnc(self):
"""Test that api version text is correctly parsed."""
resp = parse_version_text()
latest_version = INVENTREE_API_VERSION
self.assertTrue(resp[f'v{latest_version}']['latest'])
# All fields except github link should exist for every version
... | Test that api version text is correctly parsed. | test_parse_version_text_fnc | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def test_info_view(self):
"""Test that we can read the 'info-view' endpoint."""
url = reverse('api-inventree-info')
response = self.get(url)
data = response.json()
self.assertIn('server', data)
self.assertIn('version', data)
self.assertIn('instance', data)
... | Test that we can read the 'info-view' endpoint. | test_info_view | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_api.py | MIT |
def setUp(self):
"""Construct sociallogin object for test cases."""
# configure SSO
InvenTreeSetting.set_setting('LOGIN_ENABLE_SSO_GROUP_SYNC', True)
InvenTreeSetting.set_setting('SSO_GROUP_KEY', 'groups')
InvenTreeSetting.set_setting(
'SSO_GROUP_MAP', '{"idp_group": ... | Construct sociallogin object for test cases. | setUp | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_group_added_to_user(self):
"""Check that a new SSO group is added to the user."""
user: User = self.sociallogin.account.user
self.assertEqual(user.groups.count(), 0)
sso.ensure_sso_groups(None, self.sociallogin)
self.assertEqual(user.groups.count(), 1)
self.asser... | Check that a new SSO group is added to the user. | test_group_added_to_user | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_group_already_exists(self):
"""Check that existing SSO group is not modified."""
user: User = self.sociallogin.account.user
user.groups.add(self.group)
self.assertEqual(user.groups.count(), 1)
self.assertEqual(user.groups.first().name, 'inventree_group')
sso.ensu... | Check that existing SSO group is not modified. | test_group_already_exists | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_remove_non_sso_group(self):
"""Check that any group not provided by IDP is removed."""
user: User = self.sociallogin.account.user
# group must be saved to database first
group = Group(name='local_group')
group.save()
user.groups.add(group)
self.assertEqua... | Check that any group not provided by IDP is removed. | test_remove_non_sso_group | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_override_default_group_with_sso_group(self):
"""The default group should be overridden if SSO groups are available."""
user: User = self.sociallogin.account.user
self.assertEqual(user.groups.count(), 0)
Group(id=42, name='default_group').save()
InvenTreeSetting.set_setti... | The default group should be overridden if SSO groups are available. | test_override_default_group_with_sso_group | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_default_group_without_sso_group(self):
"""If no SSO group is specified, the default group should be applied."""
self.sociallogin.account.extra_data = {}
user: User = self.sociallogin.account.user
self.assertEqual(user.groups.count(), 0)
Group(id=42, name='default_group')... | If no SSO group is specified, the default group should be applied. | test_default_group_without_sso_group | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_remove_groups_overrides_default_group(self):
"""If no SSO group is specified, the default group should not be added if SSO_REMOVE_GROUPS=True."""
user: User = self.sociallogin.account.user
self.sociallogin.account.extra_data = {}
self.assertEqual(user.groups.count(), 0)
... | If no SSO group is specified, the default group should not be added if SSO_REMOVE_GROUPS=True. | test_remove_groups_overrides_default_group | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_sso_group_created_if_not_exists(self):
"""If the mapped group does not exist, a new group with the same name should be created."""
self.group.delete()
self.assertEqual(Group.objects.filter(name='inventree_group').count(), 0)
sso.ensure_sso_groups(None, self.sociallogin)
... | If the mapped group does not exist, a new group with the same name should be created. | test_sso_group_created_if_not_exists | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_buildin_token(self):
"""Test the built-in token authentication."""
self.logout()
response = self.post(
'/api/auth/v1/auth/login',
{'username': self.username, 'password': self.password},
expected_code=200,
)
data = response.json()
... | Test the built-in token authentication. | test_buildin_token | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_auth.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_auth.py | MIT |
def test_error_exceptions(self):
"""Test that ignored errors are not logged."""
self.assignRole('part.view')
def check(excpected_nbr=0):
# Check that errors are empty
errors = Error.objects.all()
self.assertEqual(len(errors), excpected_nbr)
# Test no... | Test that ignored errors are not logged. | test_error_exceptions | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_middleware.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_middleware.py | MIT |
def test_add_task(self):
"""Ensure that duplicate tasks cannot be added."""
task = 'InvenTree.tasks.heartbeat'
self.assertEqual(self.get_tasks(task).count(), 0)
InvenTree.tasks.schedule_task(task, schedule_type=Schedule.MINUTES, minutes=10)
self.assertEqual(self.get_tasks(task... | Ensure that duplicate tasks cannot be added. | test_add_task | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_tasks.py | MIT |
def test_failed_task_notification(self):
"""Test that a failed task will generate a notification."""
from common.models import NotificationEntry, NotificationMessage
# Create a staff user (to ensure notifications are sent)
user = User.objects.create_user(
username='staff', p... | Test that a failed task will generate a notification. | test_failed_task_notification | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_tasks.py | MIT |
def test_api_doc(self):
"""Test that the api-doc view works."""
api_url = os.path.join(reverse('index'), 'api-doc') + '/'
response = self.client.get(api_url)
self.assertEqual(response.status_code, 200) | Test that the api-doc view works. | test_api_doc | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_views.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_views.py | MIT |
def get_index_page(self):
"""Retrieve the index page (used for subsequent unit tests)."""
response = self.client.get('/index/')
self.assertEqual(response.status_code, 200)
return str(response.content.decode()) | Retrieve the index page (used for subsequent unit tests). | get_index_page | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/test_views.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/test_views.py | MIT |
def setup_tracing(
endpoint: str,
headers: dict,
resources_input: Optional[dict] = None,
console: bool = False,
auth: Optional[dict] = None,
is_http: bool = False,
append_http: bool = True,
):
"""Set up tracing for the application in the current context.
Args:
endpoint: The ... | Set up tracing for the application in the current context.
Args:
endpoint: The endpoint to send the traces to.
headers: The headers to send with the traces.
resources_input: The resources to send with the traces.
console: Whether to output the traces to the console.
auth: Di... | setup_tracing | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/tracing.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/tracing.py | MIT |
def addUserPermission(user: User, app_name: str, model_name: str, perm: str) -> None:
"""Add a specific permission for the provided user.
Arguments:
user: The user to add the permission to
app_name: The name of the app (e.g. 'part')
model_name: The name of the model (e.g. 'location')
... | Add a specific permission for the provided user.
Arguments:
user: The user to add the permission to
app_name: The name of the app (e.g. 'part')
model_name: The name of the model (e.g. 'location')
perm: The permission to add (e.g. 'add', 'change', 'delete', 'view')
| addUserPermission | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def getMigrationFileNames(app):
"""Return a list of all migration filenames for provided app."""
local_dir = Path(__file__).parent
files = local_dir.joinpath('..', app, 'migrations').iterdir()
# Regex pattern for migration files
regex = re.compile(r'^[\d]+_.*\.py$')
migration_files = []
f... | Return a list of all migration filenames for provided app. | getMigrationFileNames | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def getOldestMigrationFile(app, exclude_extension=True, ignore_initial=True):
"""Return the filename associated with the oldest migration."""
oldest_num = -1
oldest_file = None
for f in getMigrationFileNames(app):
if ignore_initial and f.startswith('0001_initial'):
continue
... | Return the filename associated with the oldest migration. | getOldestMigrationFile | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def getNewestMigrationFile(app, exclude_extension=True):
"""Return the filename associated with the newest migration."""
newest_file = None
newest_num = -1
for f in getMigrationFileNames(app):
num = int(f.split('_')[0])
if newest_file is None or num > newest_num:
newest_num... | Return the filename associated with the newest migration. | getNewestMigrationFile | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def findOffloadedTask(
task_name: str,
clear_after: bool = False,
reverse: bool = False,
matching_args=None,
matching_kwargs=None,
):
"""Find an offloaded tasks in the background worker queue.
Arguments:
task_name: The name of the task to search for
clear_after: Clear the ta... | Find an offloaded tasks in the background worker queue.
Arguments:
task_name: The name of the task to search for
clear_after: Clear the task queue after searching
reverse: Search in reverse order (most recent first)
matching_args: List of argument names to match against
matc... | findOffloadedTask | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def findOffloadedEvent(
event_name: str,
clear_after: bool = False,
reverse: bool = False,
matching_kwargs=None,
):
"""Find an offloaded event in the background worker queue."""
return findOffloadedTask(
'plugin.base.event.events.register_event',
matching_args=[str(event_name)],
... | Find an offloaded event in the background worker queue. | findOffloadedEvent | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def setUpTestData(cls):
"""Run setup for all tests in a given class."""
super().setUpTestData()
# Create a user to log in with
cls.user = get_user_model().objects.create_user(
username=cls.username, password=cls.password, email=cls.email
)
# Create a group f... | Run setup for all tests in a given class. | setUpTestData | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def clearRoles(cls):
"""Remove all user roles from the registered user."""
for ruleset in cls.group.rule_sets.all():
ruleset.can_view = False
ruleset.can_change = False
ruleset.can_delete = False
ruleset.can_add = False
ruleset.save() | Remove all user roles from the registered user. | clearRoles | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def assignRole(cls, role=None, assign_all: bool = False, group=None):
"""Set the user roles for the registered user.
Arguments:
role: Role of the format 'rule.permission' e.g. 'part.add'
assign_all: Set to True to assign *all* roles
group: The group to assign roles t... | Set the user roles for the registered user.
Arguments:
role: Role of the format 'rule.permission' e.g. 'part.add'
assign_all: Set to True to assign *all* roles
group: The group to assign roles to (or leave None to use the group assigned to this class)
| assignRole | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def generate_exchange_rates(self):
"""Helper function which generates some exchange rates to work with."""
rates = {'AUD': 1.5, 'CAD': 1.7, 'GBP': 0.9, 'USD': 1.0}
# Create a dummy backend
ExchangeBackend.objects.create(name='InvenTreeExchange', base_currency='USD')
backend = E... | Helper function which generates some exchange rates to work with. | generate_exchange_rates | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def assertNumQueriesLessThan(
self, value, using='default', verbose=False, url=None, log_to_file=False
):
"""Context manager to check that the number of queries is less than a certain value.
Example:
with self.assertNumQueriesLessThan(10):
# Do some stuff
Ref: ht... | Context manager to check that the number of queries is less than a certain value.
Example:
with self.assertNumQueriesLessThan(10):
# Do some stuff
Ref: https://stackoverflow.com/questions/1254170/django-is-there-a-way-to-count-sql-queries-from-an-unit-test/59089020#59089020
| assertNumQueriesLessThan | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def check_response(self, url, response, expected_code=None):
"""Debug output for an unexpected response."""
# Check that the response returned the expected status code
if expected_code is not None:
if expected_code != response.status_code: # pragma: no cover
print(
... | Debug output for an unexpected response. | check_response | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def getActions(self, url):
"""Return a dict of the 'actions' available at a given endpoint.
Makes use of the HTTP 'OPTIONS' method to request this.
"""
response = self.client.options(url)
self.assertEqual(response.status_code, 200)
actions = response.data.get('actions',... | Return a dict of the 'actions' available at a given endpoint.
Makes use of the HTTP 'OPTIONS' method to request this.
| getActions | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def download_file(
self,
url,
data=None,
expected_code=None,
expected_fn=None,
decode=True,
**kwargs,
):
"""Download a file from the server, and return an in-memory file."""
response = self.client.get(url, data=data, format='json')
sel... | Download a file from the server, and return an in-memory file. | download_file | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def export_data(
self,
url,
params=None,
export_format='csv',
export_plugin='inventree-exporter',
**kwargs,
):
"""Perform a data export operation against the provided URL.
Uses the 'data_exporter' functionality to override the POST response.
... | Perform a data export operation against the provided URL.
Uses the 'data_exporter' functionality to override the POST response.
Arguments:
url: URL to perform the export operation against
params: Dictionary of parameters to pass to the export operation
export_format... | export_data | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def process_csv(
self,
file_object,
delimiter=',',
required_cols=None,
excluded_cols=None,
required_rows=None,
):
"""Helper function to process and validate a downloaded csv file."""
# Check that the correct object type has been passed
self.ass... | Helper function to process and validate a downloaded csv file. | process_csv | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/unit_test.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/unit_test.py | MIT |
def validate_physical_units(unit):
"""Ensure that a given unit is a valid physical unit."""
unit = unit.strip()
# Ignore blank units
if not unit:
return
ureg = InvenTree.conversion.get_unit_registry()
try:
ureg(unit)
except (AssertionError, AttributeError, pint.errors.Unde... | Ensure that a given unit is a valid physical unit. | validate_physical_units | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/validators.py | MIT |
def validate_currency_code(code):
"""Check that a given code is a valid currency code."""
if code not in CURRENCIES:
raise ValidationError(_('Not a valid currency code')) | Check that a given code is a valid currency code. | validate_currency_code | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/validators.py | MIT |
def allowable_url_schemes():
"""Return the list of allowable URL schemes.
In addition to the default schemes allowed by Django,
the install configuration file (config.yaml) can specify
extra schemas
"""
# Default schemes
schemes = ['http', 'https', 'ftp', 'ftps']
extra = settings.EXTRA... | Return the list of allowable URL schemes.
In addition to the default schemes allowed by Django,
the install configuration file (config.yaml) can specify
extra schemas
| allowable_url_schemes | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/validators.py | MIT |
def validate_purchase_order_reference(value):
"""Validate the 'reference' field of a PurchaseOrder."""
from order.models import PurchaseOrder
# If we get to here, run the "default" validation routine
PurchaseOrder.validate_reference_field(value) | Validate the 'reference' field of a PurchaseOrder. | validate_purchase_order_reference | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/validators.py | MIT |
def validate_sales_order_reference(value):
"""Validate the 'reference' field of a SalesOrder."""
from order.models import SalesOrder
# If we get to here, run the "default" validation routine
SalesOrder.validate_reference_field(value) | Validate the 'reference' field of a SalesOrder. | validate_sales_order_reference | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/validators.py | MIT |
def validate_overage(value):
"""Validate that a BOM overage string is properly formatted.
An overage string can look like:
- An integer number ('1' / 3 / 4)
- A decimal number ('0.123')
- A percentage ('5%' / '10 %')
"""
value = str(value).lower().strip()
# First look for a simple num... | Validate that a BOM overage string is properly formatted.
An overage string can look like:
- An integer number ('1' / 3 / 4)
- A decimal number ('0.123')
- A percentage ('5%' / '10 %')
| validate_overage | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/validators.py | MIT |
def checkMinPythonVersion():
"""Check that the Python version is at least 3.9."""
version = sys.version.split(' ')[0]
docs = 'https://docs.inventree.org/en/stable/start/intro/#python-requirements'
msg = f"""
InvenTree requires Python 3.9 or above - you are running version {version}.
- Refer to ... | Check that the Python version is at least 3.9. | checkMinPythonVersion | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeInstanceTitle():
"""Returns the InstanceTitle for the current database."""
from common.settings import get_global_setting
if get_global_setting('INVENTREE_INSTANCE_TITLE'):
return get_global_setting('INVENTREE_INSTANCE')
return 'InvenTree' | Returns the InstanceTitle for the current database. | inventreeInstanceTitle | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeVersionTuple(version=None):
"""Return the InvenTree version string as (maj, min, sub) tuple."""
if version is None:
version = INVENTREE_SW_VERSION
match = re.match(r'^.*(\d+)\.(\d+)\.(\d+).*$', str(version))
return [int(g) for g in match.groups()] | Return the InvenTree version string as (maj, min, sub) tuple. | inventreeVersionTuple | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeDocsVersion():
"""Return the version string matching the latest documentation.
Development -> "latest"
Release -> "major.minor.sub" e.g. "0.5.2"
"""
if isInvenTreeDevelopmentVersion():
return 'latest'
return INVENTREE_SW_VERSION # pragma: no cover | Return the version string matching the latest documentation.
Development -> "latest"
Release -> "major.minor.sub" e.g. "0.5.2"
| inventreeDocsVersion | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def isInvenTreeUpToDate():
"""Test if the InvenTree instance is "up to date" with the latest version.
A background task periodically queries GitHub for latest version, and stores it to the database as "_INVENTREE_LATEST_VERSION"
"""
from common.settings import get_global_setting
latest = get_globa... | Test if the InvenTree instance is "up to date" with the latest version.
A background task periodically queries GitHub for latest version, and stores it to the database as "_INVENTREE_LATEST_VERSION"
| isInvenTreeUpToDate | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def parse_version_text():
"""Parse the version text to structured data."""
patched_data = INVENTREE_API_TEXT.split('\n\n')
# Remove first newline on latest version
patched_data[0] = patched_data[0].replace('\n', '', 1)
latest_version = f'v{INVENTREE_API_VERSION}'
version_data = {}
for versi... | Parse the version text to structured data. | parse_version_text | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeApiText(versions: int = 10, start_version: int = 0):
"""Returns API version descriptors.
Args:
versions: Number of versions to return. Default: 10
start_version: first version to report. Defaults to return the latest {versions} versions.
"""
version_data = INVENTREE_API_TEX... | Returns API version descriptors.
Args:
versions: Number of versions to return. Default: 10
start_version: first version to report. Defaults to return the latest {versions} versions.
| inventreeApiText | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeInstaller():
"""Returns the installer for the running codebase - if set."""
# First look in the environment variables, e.g. if running in docker
installer = os.environ.get('INVENTREE_PKG_INSTALLER', '')
if installer:
return installer
elif settings.DOCKER:
return 'DOC'
... | Returns the installer for the running codebase - if set. | inventreeInstaller | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeBranch():
"""Returns the branch for the running codebase - if set."""
# First look in the environment variables, e.g. if running in docker
branch = os.environ.get('INVENTREE_PKG_BRANCH', '')
if branch:
return branch
if main_branch is None:
return None
return main_... | Returns the branch for the running codebase - if set. | inventreeBranch | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeTarget():
"""Returns the target platform for the running codebase - if set."""
# First look in the environment variables, e.g. if running in docker
return os.environ.get('INVENTREE_PKG_TARGET', None) | Returns the target platform for the running codebase - if set. | inventreeTarget | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def inventreeDatabase():
"""Return the InvenTree database backend e.g. 'postgresql'."""
db = settings.DATABASES['default']
return db.get('ENGINE', None).replace('django.db.backends.', '') | Return the InvenTree database backend e.g. 'postgresql'. | inventreeDatabase | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/version.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/version.py | MIT |
def auth_request(request):
"""Simple 'auth' endpoint used to determine if the user is authenticated.
Useful for (for example) redirecting authentication requests through django's permission framework.
"""
if request.user and request.user.is_authenticated:
return HttpResponse(status=200)
ret... | Simple 'auth' endpoint used to determine if the user is authenticated.
Useful for (for example) redirecting authentication requests through django's permission framework.
| auth_request | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/views.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/views.py | MIT |
def handle(self, *args, **kwargs):
"""Check for any pending database migrations."""
logger.info('Checking for pending database migrations')
check_for_migrations(force=True, reload_registry=False)
logger.info('Database migrations complete') | Check for any pending database migrations. | handle | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/management/commands/check_migrations.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/management/commands/check_migrations.py | MIT |
def handle(self, *args, **kwargs):
"""Cleanup old (undefined) settings in the database."""
logger.info('Collecting settings')
from common.models import InvenTreeSetting, InvenTreeUserSetting
# general settings
db_settings = InvenTreeSetting.objects.all()
model_settings =... | Cleanup old (undefined) settings in the database. | handle | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/management/commands/clean_settings.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/management/commands/clean_settings.py | MIT |
def add_arguments(self, parser):
"""Add custom arguments for this command."""
parser.add_argument(
'filename', type=str, help='Output filename for filter definitions'
) | Add custom arguments for this command. | add_arguments | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/management/commands/export_filters.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/management/commands/export_filters.py | MIT |
def handle(self, *args, **kwargs):
"""Export filter information to a YAML file."""
filters = discover_filters()
# Write
filename = kwargs.get('filename', 'inventree_filters.yml')
with open(filename, 'w', encoding='utf-8') as f:
yaml.dump(filters, f, indent=4)
... | Export filter information to a YAML file. | handle | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/management/commands/export_filters.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/management/commands/export_filters.py | MIT |
def discover_filters():
"""Discover all available filters.
This function is a copy of a function from the Django 'admindocs' module in django.contrib.admindocs.views.TemplateFilterIndexView
"""
filters = []
try:
engine = Engine.get_default()
except ImproperlyConfigured:
# Non-tr... | Discover all available filters.
This function is a copy of a function from the Django 'admindocs' module in django.contrib.admindocs.views.TemplateFilterIndexView
| discover_filters | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/management/commands/export_filters.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/management/commands/export_filters.py | MIT |
def get_type_str(type_obj):
"""Get the type str of a type object, including any generic parameters."""
if type_obj is django.db.models.QuerySet:
raise CommandError(
'INVE-E3 - Do not use django.db.models.QuerySet directly for typing, use report.mixins.QuerySet instead.'
)
if ori... | Get the type str of a type object, including any generic parameters. | get_type_str | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/management/commands/export_report_context.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/management/commands/export_report_context.py | MIT |
def parse_docstring(docstring: str):
"""Parse the docstring of a type object and return a dictionary of sections."""
sections = {}
current_section = None
for line in docstring.splitlines():
stripped = line.strip()
if not stripped:
continue
if stripped.endswith(':')... | Parse the docstring of a type object and return a dictionary of sections. | parse_docstring | python | inventree/InvenTree | src/backend/InvenTree/InvenTree/management/commands/export_report_context.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/InvenTree/management/commands/export_report_context.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.