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_tag_safe_url(self): """Test that the safe url tag works expected.""" # right url self.assertEqual( plugin_tags.safe_url('api-plugin-install'), '/api/plugins/install/' ) # wrong url self.assertEqual(plugin_tags.safe_url('indexas'), None)
Test that the safe url tag works expected.
test_tag_safe_url
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def test_depreciation(self): """Check if depreciations raise as expected.""" # check deprecation warning is firing with self.assertWarns(DeprecationWarning): self.assertEqual(self.plugin_old.slug, 'old') # check default value is used self.assertEqual( ...
Check if depreciations raise as expected.
test_depreciation
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def run_package_test(self, directory): """General runner for testing package based installs.""" # Patch environment variable to add dir envs = {'INVENTREE_PLUGIN_TEST_DIR': directory} with mock.patch.dict(os.environ, envs): # Reload to rediscover plugins registry....
General runner for testing package based installs.
run_package_test
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def test_custom_loading(self): """Test if data in custom dir is loaded correctly.""" test_dir = Path('plugin_test_dir') # Patch env envs = {'INVENTREE_PLUGIN_TEST_DIR': 'plugin_test_dir'} with mock.patch.dict(os.environ, envs): # Run plugin directory discovery again ...
Test if data in custom dir is loaded correctly.
test_custom_loading
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def test_folder_loading(self): """Test that plugins in folders outside of BASE_DIR get loaded.""" # Run in temporary directory -> always a new random name with tempfile.TemporaryDirectory() as tmp: # Fill directory with sample data new_dir = Path(tmp).joinpath('mock') ...
Test that plugins in folders outside of BASE_DIR get loaded.
test_folder_loading
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def test_package_loading(self): """Test that package distributed plugins work.""" # Install sample package subprocess.check_output(['pip', 'install', 'inventree-zapier']) # Reload to discover plugin registry.reload_plugins(full_reload=True, collect=True) # Test that plu...
Test that package distributed plugins work.
test_package_loading
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def test_broken_samples(self): """Test that the broken samples trigger reloads.""" # In the base setup there are no errors self.assertEqual(len(registry.errors), 0) # Reload the registry with the broken samples dir brokenDir = str(Path(__file__).parent.joinpath('broken').absolut...
Test that the broken samples trigger reloads.
test_broken_samples
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def test_registry_reload(self): """Test that the registry correctly reloads plugin modules. - Create a simple plugin which we can change the version - Ensure that the "hash" of the plugin registry changes """ dummy_file = os.path.join(PLUGIN_TEST_DIR, 'dummy_ci_plugin.py') ...
Test that the registry correctly reloads plugin modules. - Create a simple plugin which we can change the version - Ensure that the "hash" of the plugin registry changes
test_registry_reload
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def plugin_content(version): """Return the content of the plugin file.""" content = f""" from plugin import InvenTreePlugin PLG_VERSION = "{version}" print(">>> LOADING DUMMY PLUGIN v" + PLG_VERSION + " <<<") class DummyCIPlugin(InvenTreePlugin)...
Return the content of the plugin file.
plugin_content
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def create_plugin_file( version: str, enabled: bool = True, reload: bool = True ) -> str: """Create a plugin file with the given version. Arguments: version: The version string to use for the plugin file enabled: Whether the plugin should be e...
Create a plugin file with the given version. Arguments: version: The version string to use for the plugin file enabled: Whether the plugin should be enabled or not reload: Whether to reload the plugin registry after creating the file Returns: ...
create_plugin_file
python
inventree/InvenTree
src/backend/InvenTree/plugin/test_plugin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/test_plugin.py
MIT
def get_plugin_urls(): """Returns a urlpattern that can be integrated into the global urls.""" from plugin.registry import registry urls = [] if get_global_setting('ENABLE_PLUGINS_URL', False) or settings.PLUGIN_TESTING_SETUP: for plugin in registry.plugins.values(): if plugin.mixi...
Returns a urlpattern that can be integrated into the global urls.
get_plugin_urls
python
inventree/InvenTree
src/backend/InvenTree/plugin/urls.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/urls.py
MIT
def action_name(self): """Action name for this plugin. If the ACTION_NAME parameter is empty, uses the NAME instead. """ if self.ACTION_NAME: return self.ACTION_NAME return self.name
Action name for this plugin. If the ACTION_NAME parameter is empty, uses the NAME instead.
action_name
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/action/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/action/mixins.py
MIT
def get_response(self, user=None, data=None): """Return a response. Default implementation is a simple response which can be overridden. """ return { 'action': self.action_name(), 'result': self.get_result(user, data), 'info': self.get_info(user, data...
Return a response. Default implementation is a simple response which can be overridden.
get_response
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/action/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/action/mixins.py
MIT
def setUp(self): """Setup environment for tests. Contains multiple sample plugins that are used in the tests """ class SimplePlugin(ActionMixin, InvenTreePlugin): pass self.plugin = SimplePlugin() class TestActionPlugin(ActionMixin, InvenTreePlugin): ...
Setup environment for tests. Contains multiple sample plugins that are used in the tests
setUp
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/action/test_action.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/action/test_action.py
MIT
def test_post_errors(self): """Check the possible errors with post.""" # Test empty request response = self.client.post('/api/action/') self.assertEqual(response.status_code, 200) self.assertEqual(response.data, {'error': 'No action specified'}) # Test non-existing actio...
Check the possible errors with post.
test_post_errors
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/action/test_action.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/action/test_action.py
MIT
def log_scan(self, request, response=None, result: bool = False): """Log a barcode scan to the database. Arguments: request: HTTP request object response: Optional response data result: Boolean indicating success or failure of the scan """ from common...
Log a barcode scan to the database. Arguments: request: HTTP request object response: Optional response data result: Boolean indicating success or failure of the scan
log_scan
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def create(self, request, *args, **kwargs): """Handle create method - override default create.""" serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except Exception as exc: self.log_scan(request, response={'error':...
Handle create method - override default create.
create
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def handle_barcode(self, barcode: str, request, **kwargs): """Handle barcode scan. Arguments: barcode: Raw barcode value request: HTTP request object kwargs: Any custom fields passed by the specific serializer """ raise NotImplementedError( ...
Handle barcode scan. Arguments: barcode: Raw barcode value request: HTTP request object kwargs: Any custom fields passed by the specific serializer
handle_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def scan_barcode(self, barcode: str, request, **kwargs): """Perform a generic 'scan' of the provided barcode data. Check each loaded plugin, and return the first valid match """ plugins = registry.with_mixin(PluginMixinEnum.BARCODE) # Look for a barcode plugin which knows how t...
Perform a generic 'scan' of the provided barcode data. Check each loaded plugin, and return the first valid match
scan_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def handle_barcode(self, barcode: str, request, **kwargs): """Perform barcode scan action. Arguments: barcode: Raw barcode value request: HTTP request object kwargs: Any custom fields passed by the specific serializer """ response = self.scan...
Perform barcode scan action. Arguments: barcode: Raw barcode value request: HTTP request object kwargs: Any custom fields passed by the specific serializer
handle_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def handle_barcode(self, barcode: str, request, **kwargs): """Respond to a barcode assign request. Checks inputs and assign barcode (hash) to StockItem. """ # Here we only check against 'InvenTree' plugins inventree_barcode_plugin = registry.get_plugin('inventreebarcode') ...
Respond to a barcode assign request. Checks inputs and assign barcode (hash) to StockItem.
handle_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def get_supplier_part( self, purchase_order, part=None, supplier_part=None, manufacturer_part=None ): """Return a single matching SupplierPart (or else raise an exception). Arguments: purchase_order: PurchaseOrder object part: Part object (optional) suppl...
Return a single matching SupplierPart (or else raise an exception). Arguments: purchase_order: PurchaseOrder object part: Part object (optional) supplier_part: SupplierPart object (optional) manufacturer_part: ManufacturerPart object (optional) Returns: ...
get_supplier_part
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def handle_barcode(self, barcode: str, request, **kwargs): """Handle a barcode scan for a purchase order item.""" logger.debug("BarcodePOReceive: scanned barcode - '%s'", barcode) # Extract optional fields from the dataset supplier = kwargs.get('supplier') purchase_order = kwarg...
Handle a barcode scan for a purchase order item.
handle_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def get_line_item(self, stock_item, **kwargs): """Return the matching line item for the provided stock item. Raises: ValidationError: If no single matching line item is found """ # Extract sales order object (required field) sales_order = kwargs['sales_order'] ...
Return the matching line item for the provided stock item. Raises: ValidationError: If no single matching line item is found
get_line_item
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def get_shipment(self, **kwargs): """Extract the shipment from the provided kwargs, or guess. Raises: ValidationError: If the shipment does not match the sales order """ sales_order = kwargs['sales_order'] if shipment := kwargs.get('shipment'): if shipme...
Extract the shipment from the provided kwargs, or guess. Raises: ValidationError: If the shipment does not match the sales order
get_shipment
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def handle_barcode(self, barcode: str, request, **kwargs): """Handle barcode scan for sales order allocation. Arguments: barcode: Raw barcode data request: HTTP request object kwargs: sales_order: SalesOrder ID value (required) line: SalesOrderLi...
Handle barcode scan for sales order allocation. Arguments: barcode: Raw barcode data request: HTTP request object kwargs: sales_order: SalesOrder ID value (required) line: SalesOrderLineItem ID value (optional) shipment: SalesOrderShipment ID...
handle_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def get_queryset(self): """Return the queryset for the BarcodeScan API.""" queryset = super().get_queryset() # Pre-fetch user data queryset = queryset.prefetch_related('user') return queryset
Return the queryset for the BarcodeScan API.
get_queryset
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/api.py
MIT
def cache(func): """Cache the result of a function, but do not cache falsy results.""" cache = {} def wrapper(): """Wrapper function for caching.""" if 'default' not in cache: res = func() if res: cache['default'] = res return res ...
Cache the result of a function, but do not cache falsy results.
cache
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/helper.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/helper.py
MIT
def generate_barcode(model_instance: InvenTreeBarcodeMixin): """Generate a barcode for a given model instance.""" from common.settings import get_global_setting from plugin import registry from plugin.mixins import BarcodeMixin # Find the selected barcode generation plugin slug = get_global_set...
Generate a barcode for a given model instance.
generate_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/helper.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/helper.py
MIT
def get_supported_barcode_models_map(): """Return a mapping of barcode model types to the model class.""" return { model.barcode_model_type(): model for model in get_supported_barcode_models() }
Return a mapping of barcode model types to the model class.
get_supported_barcode_models_map
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/helper.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/helper.py
MIT
def get_supported_barcode_model_codes_map(): """Return a mapping of barcode model type codes to the model class.""" return { model.barcode_model_type_code(): model for model in get_supported_barcode_models() }
Return a mapping of barcode model type codes to the model class.
get_supported_barcode_model_codes_map
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/helper.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/helper.py
MIT
def has_barcode_generation(self): """Does this plugin support barcode generation.""" try: # Attempt to call the generate method self.generate(None) # type: ignore except NotImplementedError: # If a NotImplementedError is raised, then barcode generation is not...
Does this plugin support barcode generation.
has_barcode_generation
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def get_field_value(self, key, backup_value=None): """Return the value of a barcode field.""" fields = getattr(self, 'barcode_fields', None) or {} return fields.get(key, backup_value)
Return the value of a barcode field.
get_field_value
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def get_supplier_part(self) -> SupplierPart | None: """Return the SupplierPart object for the scanned barcode. Returns: SupplierPart object or None - Filter by the Supplier ID associated with the plugin - Filter by SKU (if available) - If more than one match is foun...
Return the SupplierPart object for the scanned barcode. Returns: SupplierPart object or None - Filter by the Supplier ID associated with the plugin - Filter by SKU (if available) - If more than one match is found, filter by MPN (if available)
get_supplier_part
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def get_manufacturer_part(self) -> ManufacturerPart | None: """Return the ManufacturerPart object for the scanned barcode. Returns: ManufacturerPart object or None """ mpn = self.manufacturer_part_number if not mpn: return None parts = Manufactu...
Return the ManufacturerPart object for the scanned barcode. Returns: ManufacturerPart object or None
get_manufacturer_part
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def get_purchase_order(self) -> PurchaseOrder | None: """Extract the PurchaseOrder object from the barcode fields. Inspect the customer_order_number and supplier_order_number fields, and try to find a matching PurchaseOrder object. Returns: PurchaseOrder object or None ...
Extract the PurchaseOrder object from the barcode fields. Inspect the customer_order_number and supplier_order_number fields, and try to find a matching PurchaseOrder object. Returns: PurchaseOrder object or None
get_purchase_order
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def extract_barcode_fields(self, barcode_data: str) -> dict[str, str]: """Method to extract barcode fields from barcode data. This method should return a dict object where the keys are the field names, as per the "standard field names" (defined in the SuppliedBarcodeMixin class). This ...
Method to extract barcode fields from barcode data. This method should return a dict object where the keys are the field names, as per the "standard field names" (defined in the SuppliedBarcodeMixin class). This method *must* be implemented by each plugin Returns: A dict o...
extract_barcode_fields
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def scan(self, barcode_data: str) -> dict: """Perform a generic 'scan' operation on a supplier barcode. The supplier barcode may provide sufficient information to match against one of the following model types: - SupplierPart - ManufacturerPart - PurchaseOrder -...
Perform a generic 'scan' operation on a supplier barcode. The supplier barcode may provide sufficient information to match against one of the following model types: - SupplierPart - ManufacturerPart - PurchaseOrder - PurchaseOrderLineItem (todo) - StockItem (tod...
scan
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def scan_receive_item( self, barcode_data: str, user, supplier=None, line_item=None, purchase_order=None, location=None, auto_allocate: bool = True, **kwargs, ) -> dict | None: """Attempt to receive an item against a PurchaseOrder via b...
Attempt to receive an item against a PurchaseOrder via barcode scanning. Arguments: barcode_data: The raw barcode data user: The User performing the action supplier: The Company object to receive against (or None) purchase_order: The PurchaseOrder object to recei...
scan_receive_item
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def get_supplier(self, cache: bool = False) -> Company | None: """Get the supplier for the SUPPLIER_ID set in the plugin settings. If it's not defined, try to guess it and set it if possible. """ if not isinstance(self, SettingsMixin): return None def _cache_supplie...
Get the supplier for the SUPPLIER_ID set in the plugin settings. If it's not defined, try to guess it and set it if possible.
get_supplier
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def _cache_supplier(supplier): """Cache and return the supplier object.""" if cache: self._supplier = supplier return supplier
Cache and return the supplier object.
_cache_supplier
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def ecia_field_map(cls): """Return a dict mapping ECIA field names to internal field names. Ref: https://www.ecianow.org/assets/docs/ECIA_Specifications.pdf Note that a particular plugin may need to reimplement this method, if it does not use the standard field names. """ ...
Return a dict mapping ECIA field names to internal field names. Ref: https://www.ecianow.org/assets/docs/ECIA_Specifications.pdf Note that a particular plugin may need to reimplement this method, if it does not use the standard field names.
ecia_field_map
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def parse_ecia_barcode2d(cls, barcode_data: str) -> dict[str, str]: """Parse a standard ECIA 2D barcode. Ref: https://www.ecianow.org/assets/docs/ECIA_Specifications.pdf Arguments: barcode_data: The raw barcode data Returns: A dict containing the parsed barcode...
Parse a standard ECIA 2D barcode. Ref: https://www.ecianow.org/assets/docs/ECIA_Specifications.pdf Arguments: barcode_data: The raw barcode data Returns: A dict containing the parsed barcode fields
parse_ecia_barcode2d
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def split_fields( barcode_data: str, delimiter: str = ',', header: str = '', trailer: str = '' ) -> list[str]: """Generic method for splitting barcode data into separate fields.""" if header and barcode_data.startswith(header): barcode_data = barcode_data[len(header) :] ...
Generic method for splitting barcode data into separate fields.
split_fields
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def parse_isoiec_15434_barcode2d(barcode_data: str) -> list[str]: """Parse a ISO/IEC 15434 barcode, returning the split data section.""" OLD_MOUSER_HEADER = '>[)>06\x1d' HEADER = '[)>\x1e06\x1d' TRAILER = '\x1e\x04' DELIMITER = '\x1d' # Some old mouser barcodes start wit...
Parse a ISO/IEC 15434 barcode, returning the split data section.
parse_isoiec_15434_barcode2d
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/mixins.py
MIT
def __init__(self, *args, **kwargs): """Generate serializer fields for each supported model type.""" super().__init__(*args, **kwargs) for model in plugin.base.barcodes.helper.get_supported_barcode_models(): self.fields[model.barcode_model_type()] = ( serializers.Pri...
Generate serializer fields for each supported model type.
__init__
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/serializers.py
MIT
def generateBarcode(self, model: str, pk: int, expected_code: int): """Post barcode generation and return barcode contents.""" return self.post( self.generate_url, data={'model': model, 'pk': pk}, expected_code=expected_code, )
Post barcode generation and return barcode contents.
generateBarcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_empty(self): """Test an empty barcode scan. Ensure that all required data is in the response. """ response = self.postBarcode(self.scan_url, '', expected_code=400) data = response.data self.assertIn('barcode', data) self.assertIn('This field may not be...
Test an empty barcode scan. Ensure that all required data is in the response.
test_empty
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_find_part(self): """Test that we can lookup a part based on ID.""" part = Part.objects.first() response = self.post( self.scan_url, {'barcode': f'{{"part": {part.pk}}}'}, expected_code=200 ) self.assertIn('part', response.data) self.assertIn('barcod...
Test that we can lookup a part based on ID.
test_find_part
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_find_stock_item(self): """Test that we can lookup a stock item based on ID.""" item = StockItem.objects.first() # Save barcode scan results to database set_global_setting('BARCODE_STORE_RESULTS', True) n = BarcodeScanResult.objects.count() response = self.post...
Test that we can lookup a stock item based on ID.
test_find_stock_item
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_invalid_item(self): """Test response for invalid stock item.""" response = self.post( self.scan_url, {'barcode': '{"stockitem": 999999999}'}, expected_code=400 ) self.assertIn('error', response.data)
Test response for invalid stock item.
test_invalid_item
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_find_location(self): """Test that we can lookup a stock location based on ID.""" response = self.post( self.scan_url, {'barcode': '{"stocklocation": 1}'}, expected_code=200 ) self.assertIn('stocklocation', response.data) self.assertIn('barcode_data', respons...
Test that we can lookup a stock location based on ID.
test_find_location
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_invalid_location(self): """Test response for an invalid location.""" response = self.post( self.scan_url, {'barcode': '{"stocklocation": 999999999}'}, expected_code=400, ) self.assertIn('error', response.data)
Test response for an invalid location.
test_invalid_location
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_integer_barcode(self): """Test scan of an integer barcode.""" response = self.postBarcode(self.scan_url, '123456789', expected_code=400) data = response.data self.assertIn('error', data)
Test scan of an integer barcode.
test_integer_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_array_barcode(self): """Test scan of barcode with string encoded array.""" response = self.postBarcode(self.scan_url, "['foo', 'bar']", expected_code=400) data = response.data self.assertIn('error', data)
Test scan of barcode with string encoded array.
test_array_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_barcode_scan(self): """Test that a barcode is generated with a scan.""" item = StockItem.objects.get(pk=522) response = self.postBarcode( self.scan_url, item.format_barcode(), expected_code=200 ) data = response.data self.assertIn('stockitem', data)...
Test that a barcode is generated with a scan.
test_barcode_scan
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_barcode_generation(self): """Test that a barcode can be generated for a StockItem.""" item = StockItem.objects.get(pk=522) data = self.generateBarcode('stockitem', item.pk, expected_code=200).data self.assertEqual(data['barcode'], '{"stockitem": 522}')
Test that a barcode can be generated for a StockItem.
test_barcode_generation
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_barcode_generation_invalid(self): """Test barcode generation for invalid model/pk.""" self.generateBarcode('invalidmodel', 1, expected_code=400) self.generateBarcode('stockitem', 99999999, expected_code=400)
Test barcode generation for invalid model/pk.
test_barcode_generation_invalid
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_association(self): """Test that a barcode can be associated with a StockItem.""" item = StockItem.objects.get(pk=522) self.assignRole('stock.change') self.assertEqual(len(item.barcode_hash), 0) barcode_data = 'A-TEST-BARCODE-STRING' response = self.post( ...
Test that a barcode can be associated with a StockItem.
test_association
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_unassign_endpoint(self): """Test that the unassign endpoint works as expected.""" invalid_keys = ['cat', 'dog', 'fish'] # Invalid key should fail for k in invalid_keys: response = self.post(self.unassign_url, {k: 123}, expected_code=400) self.assertIn('...
Test that the unassign endpoint works as expected.
test_unassign_endpoint
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_no_data(self): """Test when no data is provided.""" result = self.postBarcode('', expected_code=400) self.assertIn('This field may not be blank', str(result['barcode'])) self.assertIn('This field is required', str(result['sales_order']))
Test when no data is provided.
test_no_data
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_invalid_sales_order(self): """Test when an invalid sales order is provided.""" # Test with an invalid sales order ID result = self.postBarcode('', sales_order=999999999, expected_code=400) self.assertIn('object does not exist', str(result['sales_order']))
Test when an invalid sales order is provided.
test_invalid_sales_order
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def test_invalid_barcode(self): """Test when an invalid barcode is provided (does not match stock item).""" # Test with an invalid barcode result = self.postBarcode( '123456789', sales_order=self.sales_order.pk, expected_code=400 ) self.assertIn('No matching plugin f...
Test when an invalid barcode is provided (does not match stock item).
test_invalid_barcode
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py
MIT
def trigger_event(event: str, *args, **kwargs) -> None: """Trigger an event with optional arguments. Arguments: event: The event to trigger *args: Additional arguments to pass to the event handler **kwargs: Additional keyword arguments to pass to the event handler This event will b...
Trigger an event with optional arguments. Arguments: event: The event to trigger *args: Additional arguments to pass to the event handler **kwargs: Additional keyword arguments to pass to the event handler This event will be stored in the database, and the worker will respond to it lat...
trigger_event
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/event/events.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/event/events.py
MIT
def register_event(event, *args, **kwargs): """Register the event with any interested plugins. Note: This function is processed by the background worker, as it performs multiple database access operations. """ logger.debug("Registering triggered event: '%s'", event) # Determine if there are an...
Register the event with any interested plugins. Note: This function is processed by the background worker, as it performs multiple database access operations.
register_event
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/event/events.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/event/events.py
MIT
def process_event(plugin_slug, event, *args, **kwargs): """Respond to a triggered event. This function is run by the background worker process. This function may queue multiple functions to be handled by the background worker. """ plugin = registry.get_plugin(plugin_slug) if plugin is None: #...
Respond to a triggered event. This function is run by the background worker process. This function may queue multiple functions to be handled by the background worker.
process_event
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/event/events.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/event/events.py
MIT
def allow_table_event(table_name): """Determine if an automatic event should be fired for a given table. We *do not* want events to be fired for some tables! """ # Prevent table events during the data import process if isImportingData(): return False # pragma: no cover # Prevent table...
Determine if an automatic event should be fired for a given table. We *do not* want events to be fired for some tables!
allow_table_event
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/event/events.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/event/events.py
MIT
def after_save(sender, instance, created, **kwargs): """Trigger an event whenever a database entry is saved.""" table = sender.objects.model._meta.db_table instance_id = getattr(instance, 'id', None) if instance_id is None: return if not allow_table_event(table): return if cr...
Trigger an event whenever a database entry is saved.
after_save
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/event/events.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/event/events.py
MIT
def after_delete(sender, instance, **kwargs): """Trigger an event whenever a database entry is deleted.""" table = sender.objects.model._meta.db_table if not allow_table_event(table): return instance_id = None if instance: instance_id = getattr(instance, 'id', None) trigger_e...
Trigger an event whenever a database entry is deleted.
after_delete
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/event/events.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/event/events.py
MIT
def icon_packs(self) -> list[IconPack]: """Return a list of custom icon packs.""" raise MixinNotImplementedError( f"{__class__} is missing the 'icon_packs' method" )
Return a list of custom icon packs.
icon_packs
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/icons/mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/icons/mixins.py
MIT
def has_api_call(self): """Is the mixin ready to call external APIs?""" if not bool(self.API_URL_SETTING): raise MixinNotImplementedError('API_URL_SETTING must be defined') if not bool(self.API_TOKEN_SETTING): raise MixinNotImplementedError('API_TOKEN_SETTING must be defi...
Is the mixin ready to call external APIs?
has_api_call
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/APICallMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/APICallMixin.py
MIT
def api_headers(self): """Returns the default headers for requests with api_call. Contains a header with the key set in `API_TOKEN` for the plugin it `API_TOKEN_SETTING` is defined. Check the mixin class docstring for a full example. """ headers = {'Content-Type': 'application/j...
Returns the default headers for requests with api_call. Contains a header with the key set in `API_TOKEN` for the plugin it `API_TOKEN_SETTING` is defined. Check the mixin class docstring for a full example.
api_headers
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/APICallMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/APICallMixin.py
MIT
def api_build_url_args(self, arguments: dict) -> str: """Returns an encoded path for the provided dict.""" groups = [] for key, val in arguments.items(): if isinstance(val, Iterable) and not isinstance(val, str): val = ','.join([str(a) for a in val]) group...
Returns an encoded path for the provided dict.
api_build_url_args
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/APICallMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/APICallMixin.py
MIT
def _activate_mixin( cls, registry, plugins, force_reload=False, full_reload: bool = False, _internal: Optional[list] = None, *args, **kwargs, ): """Activate AppMixin plugins - add custom apps and reload. Args: registry (Pl...
Activate AppMixin plugins - add custom apps and reload. Args: registry (PluginRegistry): The registry that should be used plugins (dict): List of IntegrationPlugins that should be installed force_reload (bool, optional): Only reload base apps. Defaults to False. ...
_activate_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/AppMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/AppMixin.py
MIT
def _deactivate_mixin(cls, registry, force_reload: bool = False): """Deactivate AppMixin plugins - some magic required. Args: registry (PluginRegistry): The registry that should be used force_reload (bool, optional): Also reload base apps. Defaults to False. """ ...
Deactivate AppMixin plugins - some magic required. Args: registry (PluginRegistry): The registry that should be used force_reload (bool, optional): Also reload base apps. Defaults to False.
_deactivate_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/AppMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/AppMixin.py
MIT
def _reregister_contrib_apps(self, registry): """Fix reloading of contrib apps - models and admin. This is needed if plugins were loaded earlier and then reloaded as models and admins rely on imports. Those register models and admin in their respective objects (e.g. admin.site for admin). ...
Fix reloading of contrib apps - models and admin. This is needed if plugins were loaded earlier and then reloaded as models and admins rely on imports. Those register models and admin in their respective objects (e.g. admin.site for admin).
_reregister_contrib_apps
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/AppMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/AppMixin.py
MIT
def _get_plugin_path(cls, plugin): """Parse plugin path. The input can be either: - a local file / dir - a package """ path = plugin.path() custom_plugins_dir = get_plugin_dir() if path.is_relative_to(settings.BASE_DIR): # Plugins which are l...
Parse plugin path. The input can be either: - a local file / dir - a package
_get_plugin_path
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/AppMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/AppMixin.py
MIT
def update_exchange_rates(self, base_currency: str, symbols: list[str]) -> dict: """Update currency exchange rates. This method *must* be implemented by the plugin class. Arguments: base_currency: The base currency to use for exchange rates symbols: A list of currency s...
Update currency exchange rates. This method *must* be implemented by the plugin class. Arguments: base_currency: The base currency to use for exchange rates symbols: A list of currency symbols to retrieve exchange rates for Returns: A dictionary of exchange...
update_exchange_rates
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/CurrencyExchangeMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/CurrencyExchangeMixin.py
MIT
def supports_export( self, model_class: type, user: User, serializer_class: serializers.Serializer = None, view_class: views.APIView = None, *args, **kwargs, ) -> bool: """Return True if this plugin supports exporting data for the given model. ...
Return True if this plugin supports exporting data for the given model. Args: model_class: The model class to check user: The user requesting the export serializer_class: The serializer class to use for exporting the data view_class: The view class to use for exp...
supports_export
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/DataExport.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/DataExport.py
MIT
def generate_filename(self, model_class, export_format: str) -> str: """Generate a filename for the exported data.""" model = model_class.__name__ date = current_date().isoformat() return f'InvenTree_{model}_{date}.{export_format}'
Generate a filename for the exported data.
generate_filename
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/DataExport.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/DataExport.py
MIT
def update_headers( self, headers: OrderedDict, context: dict, **kwargs ) -> OrderedDict: """Update the headers for the data export. Allows for optional modification of the headers for the data export. Arguments: headers: The current headers for the export c...
Update the headers for the data export. Allows for optional modification of the headers for the data export. Arguments: headers: The current headers for the export context: The context for the export (provided by the plugin serializer) Returns: The updated headers ...
update_headers
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/DataExport.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/DataExport.py
MIT
def export_data( self, queryset: QuerySet, serializer_class: serializers.Serializer, headers: OrderedDict, context: dict, output: DataOutput, **kwargs, ) -> list: """Export data from the queryset. This method should be implemented by the plugi...
Export data from the queryset. This method should be implemented by the plugin to provide the actual data export functionality. Arguments: queryset: The queryset to export serializer_class: The serializer class to use for exporting the data headers: The head...
export_data
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/DataExport.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/DataExport.py
MIT
def get_export_options_serializer( self, **kwargs ) -> Union[serializers.Serializer, None]: """Return a serializer class with dynamic export options for this plugin. Returns: A class instance of a DRF serializer class, by default this an instance of self.ExportOption...
Return a serializer class with dynamic export options for this plugin. Returns: A class instance of a DRF serializer class, by default this an instance of self.ExportOptionsSerializer using the *args, **kwargs if existing for this plugin
get_export_options_serializer
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/DataExport.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/DataExport.py
MIT
def setup_navigation(self): """Setup navigation links for this plugin.""" nav_links = getattr(self, 'NAVIGATION', None) if nav_links: # check if needed values are configured for link in nav_links: if False in [a in link for a in ('link', 'name')]: ...
Setup navigation links for this plugin.
setup_navigation
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/NavigationMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/NavigationMixin.py
MIT
def add_report_context(self, report_instance, model_instance, request, context): """Add extra context to the provided report instance. By default, this method does nothing. Args: report_instance: The report instance to add context to model_instance: The model instance w...
Add extra context to the provided report instance. By default, this method does nothing. Args: report_instance: The report instance to add context to model_instance: The model instance which initiated the report generation request: The request object which initiated...
add_report_context
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/ReportMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/ReportMixin.py
MIT
def add_label_context(self, label_instance, model_instance, request, context): """Add extra context to the provided label instance. By default, this method does nothing. Args: label_instance: The label instance to add context to model_instance: The model instance which ...
Add extra context to the provided label instance. By default, this method does nothing. Args: label_instance: The label instance to add context to model_instance: The model instance which initiated the label generation request: The request object which initiated the...
add_label_context
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/ReportMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/ReportMixin.py
MIT
def report_callback(self, template, instance, report, request, **kwargs): """Callback function called after a report is generated. Arguments: template: The ReportTemplate model instance: The instance of the target model report: The generated report object ...
Callback function called after a report is generated. Arguments: template: The ReportTemplate model instance: The instance of the target model report: The generated report object request: The initiating request object The default implementation does noth...
report_callback
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/ReportMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/ReportMixin.py
MIT
def _activate_mixin(cls, registry, plugins, *args, **kwargs): """Activate schedules from plugins with the ScheduleMixin.""" logger.debug('Activating plugin tasks') # List of tasks we have activated task_keys = [] if settings.PLUGIN_TESTING or get_global_setting('ENABLE_PLUGINS_...
Activate schedules from plugins with the ScheduleMixin.
_activate_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
MIT
def validate_scheduled_tasks(self): """Check that the provided scheduled tasks are valid.""" if not self.has_scheduled_tasks: raise MixinImplementationError('SCHEDULED_TASKS not defined') for key, task in self.scheduled_tasks.items(): if 'func' not in task: ...
Check that the provided scheduled tasks are valid.
validate_scheduled_tasks
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
MIT
def register_tasks(self): """Register the tasks with the database.""" self.scheduled_tasks = self.get_scheduled_tasks() self.validate_scheduled_tasks() try: from django_q.models import Schedule for key, task in self.scheduled_tasks.items(): task_...
Register the tasks with the database.
register_tasks
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
MIT
def unregister_tasks(self): """Deregister the tasks with the database.""" try: from django_q.models import Schedule for key in self.scheduled_tasks: task_name = self.get_task_name(key) try: scheduled_task = Schedule.objects.ge...
Deregister the tasks with the database.
unregister_tasks
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/ScheduleMixin.py
MIT
def _activate_mixin(cls, registry, plugins, *args, **kwargs): """Activate plugin settings. Add all defined settings form the plugins to a unified dict in the registry. This dict is referenced by the PluginSettings for settings definitions. """ logger.debug('Activating plugin set...
Activate plugin settings. Add all defined settings form the plugins to a unified dict in the registry. This dict is referenced by the PluginSettings for settings definitions.
_activate_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
MIT
def get_setting(self, key, cache=False, backup_value=None): """Return the 'value' of the setting associated with this plugin. Arguments: key: The 'name' of the setting value to be retrieved cache: Whether to use RAM cached value (default = False) backup_value: A back...
Return the 'value' of the setting associated with this plugin. Arguments: key: The 'name' of the setting value to be retrieved cache: Whether to use RAM cached value (default = False) backup_value: A backup value to return if the setting is not found
get_setting
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
MIT
def set_setting(self, key, value, user=None): """Set plugin setting value by key.""" from plugin.models import PluginSetting from plugin.registry import registry try: plugin = registry.get_plugin_config(self.plugin_slug(), self.plugin_name()) except (OperationalError...
Set plugin setting value by key.
set_setting
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
MIT
def check_settings(self): """Check if all required settings for this machine are defined. Warning: This method cannot be used in the __init__ function of the plugin Returns: is_valid: Are all required settings defined missing_settings: List of all settings that are miss...
Check if all required settings for this machine are defined. Warning: This method cannot be used in the __init__ function of the plugin Returns: is_valid: Are all required settings defined missing_settings: List of all settings that are missing (empty if is_valid is 'True') ...
check_settings
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
MIT
def get_settings_dict(self) -> dict: """Return a dictionary of all settings for this plugin. - For each setting, return <key>: <value> pair. - If the setting is not defined, return the default value (if defined). Returns: dict: Dictionary of all settings for this plugin ...
Return a dictionary of all settings for this plugin. - For each setting, return <key>: <value> pair. - If the setting is not defined, return the default value (if defined). Returns: dict: Dictionary of all settings for this plugin
get_settings_dict
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
MIT
def test_mixin_name(self): """Test that the mixin registers itself correctly.""" # mixin name self.assertIn( self.MIXIN_NAME, {item['key'] for item in self.mixin.registered_mixins.values()}, ) # human name self.assertIn( self.MIXIN_HUMA...
Test that the mixin registers itself correctly.
test_mixin_name
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/test_mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/test_mixins.py
MIT
def test_base_setup(self): """Test that the base settings work.""" # check init self.assertTrue(self.mixin.has_api_call) # api_url self.assertEqual('https://api.github.com', self.mixin.api_url) # api_headers headers = self.mixin.api_headers self.assertEqu...
Test that the base settings work.
test_base_setup
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/test_mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/test_mixins.py
MIT
def test_args(self): """Test that building up args work.""" # api_build_url_args # 1 arg result = self.mixin.api_build_url_args({'a': 'abc123'}) self.assertEqual(result, '?a=abc123') # non string arg result = self.mixin.api_build_url_args({'a': 1}) self.as...
Test that building up args work.
test_args
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/test_mixins.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/test_mixins.py
MIT
def _activate_mixin( cls, registry, plugins, force_reload=False, full_reload: bool = False, *args, **kwargs, ): """Activate UrlsMixin plugins - add custom urls . Args: registry (PluginRegistry): The registry that should be used ...
Activate UrlsMixin plugins - add custom urls . Args: registry (PluginRegistry): The registry that should be used plugins (dict): List of IntegrationPlugins that should be installed force_reload (bool, optional): Only reload base apps. Defaults to False. full_relo...
_activate_mixin
python
inventree/InvenTree
src/backend/InvenTree/plugin/base/integration/UrlsMixin.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/base/integration/UrlsMixin.py
MIT