Skip to content

Commit

Permalink
Merge pull request #127 from inventree/getattr-bug-fix
Browse files Browse the repository at this point in the history
Bug fix for missing attribute
  • Loading branch information
SchrodingersGat committed Jul 30, 2022
2 parents 71241f9 + a30a829 commit 33bfe74
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 6 deletions.
25 changes: 19 additions & 6 deletions inventree/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,23 @@ def __init__(self, api, pk=None, data=None):
""" Instantiate this InvenTree object.
Args:
pk - The ID (primary key) associated with this object on the server
api - The request manager object
pk - The ID (primary key) associated with this object on the server
data - JSON representation of the object
"""

# If the pk is not explicitly provided,
# extract it from the provided dataset
if pk is None:
if pk is None and data:
pk = data.get('pk', None)
elif type(pk) is not int:

# Convert to integer
try:
pk = int(pk)
except Exception:
raise TypeError(f"Supplied <pk> value ({pk}) for {self.__class__} is invalid.")
elif pk <= 0:

if pk <= 0:
raise ValueError(f"Supplier <pk> value ({pk}) for {self.__class__} must be positive.")

self._url = f"{self.URL}/{pk}/"
Expand Down Expand Up @@ -117,7 +122,14 @@ def fieldNames(cls, api):
@property
def pk(self):
""" Convenience method for accessing primary-key field """
return self._data.get('pk', None)
val = self._data.get('pk', None)

try:
val = int(val)
except ValueError:
pass

return val

@classmethod
def create(cls, api, data, **kwargs):
Expand Down Expand Up @@ -242,10 +254,11 @@ def reload(self):
raise AttributeError(f"model.reload failed at '{self._url}': No API instance provided")

def __getattr__(self, name):

if name in self._data.keys():
return self._data[name]
else:
return super().__getattr__(name)
return super().__getattribute__(name)

def __getitem__(self, name):
if name in self._data.keys():
Expand Down
65 changes: 65 additions & 0 deletions test/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
Unit test for basic model class functionality
"""

import os
import sys

sys.path.append(os.path.abspath(os.path.dirname(__file__)))

from inventree.base import InventreeObject # noqa: E402
from test_api import InvenTreeTestCase # noqa: E402


class BaseModelTests(InvenTreeTestCase):
"""Simple unit tests for the InvenTreeObject class"""

def test_create(self):
"""Unit tests for InventreeObject creation"""

# Test with non-int pk
with self.assertRaises(TypeError):
InventreeObject(None, pk='test')

# Test with invalid pk
for pk in [-1, 0]:
with self.assertRaises(ValueError):
InventreeObject(None, pk=pk)

# Test with pk supplied in data
with self.assertRaises(TypeError):
InventreeObject(
None,
data={
'pk': 'seven',
}
)

def test_data_access(self):
"""Test data access functionality"""

obj = InventreeObject(
None,
data={
"pk": "10",
"hello": "world",
"name": "My name",
"description": "My description",
}
)

# Test __getattr__ access
self.assertEqual(obj.pk, 10)
self.assertEqual(obj.name, "My name")

with self.assertRaises(AttributeError):
print(obj.doesNotExist)

# Test __getitem__ access
self.assertEqual(obj['description'], 'My description')
self.assertEqual(obj['pk'], '10')
self.assertEqual(obj['hello'], 'world')

for k in ['fake', 'data', 'values']:
with self.assertRaises(KeyError):
print(obj[k])

0 comments on commit 33bfe74

Please sign in to comment.