2016-03-22 09:06:54 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
2017-12-19 04:19:57 +08:00
|
|
|
from django.db import models
|
2016-03-22 09:06:54 +08:00
|
|
|
from django.test import TestCase
|
|
|
|
|
|
|
|
from .models import DataModel
|
|
|
|
|
|
|
|
|
|
|
|
class BinaryFieldTests(TestCase):
|
|
|
|
binary_data = b"\x00\x46\xFE"
|
|
|
|
|
|
|
|
def test_set_and_retrieve(self):
|
2018-10-01 21:16:16 +08:00
|
|
|
data_set = (
|
|
|
|
self.binary_data,
|
|
|
|
bytearray(self.binary_data),
|
|
|
|
memoryview(self.binary_data),
|
|
|
|
)
|
2016-03-22 09:06:54 +08:00
|
|
|
for bdata in data_set:
|
2019-06-07 12:04:56 +08:00
|
|
|
with self.subTest(data=repr(bdata)):
|
|
|
|
dm = DataModel(data=bdata)
|
|
|
|
dm.save()
|
|
|
|
dm = DataModel.objects.get(pk=dm.pk)
|
|
|
|
self.assertEqual(bytes(dm.data), bytes(bdata))
|
|
|
|
# Resave (=update)
|
|
|
|
dm.save()
|
|
|
|
dm = DataModel.objects.get(pk=dm.pk)
|
|
|
|
self.assertEqual(bytes(dm.data), bytes(bdata))
|
|
|
|
# Test default value
|
|
|
|
self.assertEqual(bytes(dm.short_data), b"\x08")
|
2016-03-22 09:06:54 +08:00
|
|
|
|
|
|
|
def test_max_length(self):
|
|
|
|
dm = DataModel(short_data=self.binary_data * 4)
|
|
|
|
with self.assertRaises(ValidationError):
|
|
|
|
dm.full_clean()
|
2017-12-19 04:19:57 +08:00
|
|
|
|
|
|
|
def test_editable(self):
|
|
|
|
field = models.BinaryField()
|
|
|
|
self.assertIs(field.editable, False)
|
|
|
|
field = models.BinaryField(editable=True)
|
|
|
|
self.assertIs(field.editable, True)
|
|
|
|
field = models.BinaryField(editable=False)
|
|
|
|
self.assertIs(field.editable, False)
|
2018-09-27 02:38:12 +08:00
|
|
|
|
|
|
|
def test_filter(self):
|
|
|
|
dm = DataModel.objects.create(data=self.binary_data)
|
|
|
|
DataModel.objects.create(data=b"\xef\xbb\xbf")
|
|
|
|
self.assertSequenceEqual(DataModel.objects.filter(data=self.binary_data), [dm])
|
|
|
|
|
2018-10-01 21:16:16 +08:00
|
|
|
def test_filter_bytearray(self):
|
|
|
|
dm = DataModel.objects.create(data=self.binary_data)
|
|
|
|
DataModel.objects.create(data=b"\xef\xbb\xbf")
|
|
|
|
self.assertSequenceEqual(
|
|
|
|
DataModel.objects.filter(data=bytearray(self.binary_data)), [dm]
|
|
|
|
)
|
|
|
|
|
2018-09-27 02:38:12 +08:00
|
|
|
def test_filter_memoryview(self):
|
|
|
|
dm = DataModel.objects.create(data=self.binary_data)
|
|
|
|
DataModel.objects.create(data=b"\xef\xbb\xbf")
|
|
|
|
self.assertSequenceEqual(
|
|
|
|
DataModel.objects.filter(data=memoryview(self.binary_data)), [dm]
|
|
|
|
)
|