Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion qcodes/tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
make_unique, DelegateAttributes,
LogCapture, strip_attrs, full_class,
named_repr, make_sweep, is_sequence_of,
compare_dictionaries)
compare_dictionaries, NumpyJSONEncoder)
from qcodes.utils.deferred_operations import is_function


Expand Down Expand Up @@ -550,6 +550,28 @@ def test_depth(self):
with self.subTest(args=args):
self.assertFalse(is_sequence_of(*args))

# tests related to JSON encoding
class TestJSON(TestCase):

def testNumpyJSONEncoder(self):
e = NumpyJSONEncoder()

# test basic python types
testinput=[10, float(10.), 'hello', {'a': 0, 'b': 1}]
testoutput=['10', '10.0', '"hello"', '{"a": 0, "b": 1}']
# int
for d, r in zip(testinput, testoutput):
v=e.encode(d)
print(v==r)

# test numpy array
x=np.array([1,0,0])
v=e.encode(x)

# test class
class dummy(object):
pass
v=e.encode(dummy())

class TestCompareDictionaries(TestCase):
def test_same(self):
Expand Down
8 changes: 7 additions & 1 deletion qcodes/utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class NumpyJSONEncoder(json.JSONEncoder):
"""Return numpy types as standard types."""
# http://stackoverflow.com/questions/27050108/convert-numpy-type-to-python
# http://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types/11389998#11389998

def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
Expand All @@ -33,7 +34,12 @@ def default(self, obj):
'im': float(obj.imag)
}
else:
return super(NumpyJSONEncoder, self).default(obj)
try:
s = super(NumpyJSONEncoder, self).default(obj)
except TypeError:
# we cannot convert the object to JSON, just take a string
s = str(obj)
return s


def tprint(string, dt=1, tag='default'):
Expand Down
2 changes: 1 addition & 1 deletion qcodes/utils/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ def validate(self, value, context=''):
if (np.shape(value) != self._shape):
raise ValueError(
'{} does not have expected shape {}; {}'.format(
repr(value), self._shape, context))
repr(value), self._shape, context))

# Only check if max is not inf as it can be expensive for large arrays
if self._max_value != (float("inf")):
Expand Down