Ticket #18501: bug18501.shar

File bug18501.shar, 7.5 KB (added by msopacua, 3 years ago)

reproduction data

Line 
1# This is a shell archive.  Save it in a file, remove anything before
2# this line, and then unpack it by entering "sh file".  Note, it may
3# create directories; files and directories will be owned by you and
4# have default permissions.
5#
6# This archive contains:
7#
8#       devices
9#       devices/__init__.py
10#       devices/admin.py
11#       devices/models.py
12#       devices/tests.py
13#       devices/fixtures
14#       devices/fixtures/msk.json
15#
16echo c - devices
17mkdir -p devices > /dev/null 2>&1
18echo x - devices/__init__.py
19sed 's/^X//' >devices/__init__.py << 'cb149f71f097b0bc51fcd4315d659ec2'
20cb149f71f097b0bc51fcd4315d659ec2
21echo x - devices/admin.py
22sed 's/^X//' >devices/admin.py << '5441acfd00fe2f753bc5553ac68101d7'
23Xfrom devices import models
24Xfrom django.contrib import admin
25X
26Xadmin.site.register(models.DevicePciId)
275441acfd00fe2f753bc5553ac68101d7
28echo x - devices/models.py
29sed 's/^X//' >devices/models.py << '93737618aac33064567404e01de70784'
30X# vim: ts=4 sw=4 fdm=marker tw=158
31Xfrom django.db import models
32Xfrom django import forms
33Xfrom django.utils.translation import ugettext_lazy as _
34X
35Xclass HexField(models.Field):
36X    description = 'Integers provided and presented as hexadecimal strings'
37X   
38X    __metaclass__ = models.SubfieldBase
39X    def __init__(self, *args, **kwargs):
40X        if( kwargs['max_length'] % 2 != 0 ) :
41X            kwargs['max_length'] += 1
42X        if( kwargs['max_length'] > 16 ) :
43X            kwargs['max_length'] = 16
44X        kwargs['max_length'] /= 2
45X        super(HexField, self).__init__(*args, **kwargs)
46X       
47X    def db_type(self, connection) :
48X        if self.max_length > 3 :
49X            return 'BIGINT'
50X        elif self.max_length > 1 :
51X            return 'INTEGER'
52X        else :
53X            return 'SMALLINT'
54X   
55X    def to_python(self, value) :
56X        if isinstance(value, int) :
57X            if value < 0 :
58X                raise ValidationError(
59X                    "Negative values are not supported ({})".format(value))
60X           
61X            if self.max_length > 4 :
62X                fmt = '0x{:016x}'
63X            elif self.max_length > 2 :
64X                fmt = '0x{:08x}'
65X            else :
66X                fmt = '0x{:04x}'
67X            valid = fmt.format(value)
68X       
69X        elif isinstance(value, (unicode, str)) :
70X            if value == '' :
71X                valid = '0x00'
72X            else :
73X                try :
74X                    check = int(value, 16)
75X                    valid = value
76X                except ValueError:
77X                    raise ValidationError(
78X                        "Unable to convert >{}< to hexadecimal".format(value))
79X        elif value is None :
80X            if self.max_length > 4 :
81X                valid = '0x0000000000000000'
82X            elif self.max_length > 2 :
83X                valid = '0x00000000'
84X            else :
85X                valid = '0x0000'
86X        else :
87X            raise ValidationError(
88X                "Expected string or int and got {}".format(type(value)))
89X       
90X        return valid
91X
92X    def get_prep_value(self, value) :
93X        if isinstance(value, unicode) or isinstance(value, str) :
94X            val = int(value, 16)
95X        elif isinstance(value, int) :
96X            raise ValidationError(
97X                'get_prep_value called with already prepped    value'
98X            )
99X        else :
100X            raise ValidationError(
101X                "Value {} of type {} not expected".format(
102X                    value, type(value)
103X                )
104X            )
105X       
106X        return val
107X
108X    def get_prep_lookup(self, lookup_type, value) :
109X        if lookup_type == 'exact' :
110X            return self.get_prep_value(value)
111X        elif lookup_type == 'in' :
112X            return [self.get_prep_value(v) for v in value]
113X        else :
114X            raise TypeError('Unsupported lookup type')
115X
116X    def formfield(self, **kwargs) :
117X        """OVerride this later with hex-aware widget"""
118X        defaults = { 'form_class': forms.CharField }
119X        defaults.update(kwargs)
120X
121X        return super(HexField, self).formfield(**defaults)
122X
123Xclass VendorHardwareIdentifier(models.Model) :
124X    identifier = HexField(
125X        max_length=4,
126X        primary_key=True,
127X        verbose_name=_('identifier')
128X    )
129X    name = models.CharField(
130X        max_length=96,
131X        default='Unknown ID',
132X        db_index=True,
133X        verbose_name=_('name')
134X    )
135X   
136X    def __unicode__(self) :
137X        return self.name
138X   
139X    class Meta:
140X        abstract = True
141X
142Xclass HardwareDeviceIdentifier(models.Model) :
143X    identifier = HexField(
144X        max_length=4,
145X        verbose_name=_('identifier')
146X    )
147X    name = models.CharField(
148X        max_length=192,
149X        verbose_name=_('device name')
150X    )
151X
152X    def __unicode__(self) :
153X        return self.name
154X   
155X    class Meta :
156X        abstract = True
157X
158Xclass VendorPciId(VendorHardwareIdentifier) :
159X    added = models.DateField(auto_now_add=True)
160X
161Xclass DevicePciId(HardwareDeviceIdentifier) :
162X    vendor = models.ForeignKey(VendorPciId,
163X        verbose_name=_('vendor'),
164X    )
165X    added = models.DateField(auto_now_add=True)
166X
167X    class Meta :
168X        verbose_name = _('PCI device identifier')
169X        verbose_name_plural = _('PCI device identifiers')
170X        unique_together = (('vendor', 'identifier'))
171X        ordering = [ 'name' ]
17293737618aac33064567404e01de70784
173echo x - devices/tests.py
174sed 's/^X//' >devices/tests.py << '5c6e7aac64209866496e51a471254275'
175Xfrom __future__ import absolute_import
176X# vim: ts=4 sw=4 fdm=marker et tw=78 ai
177Xfrom django.test import TestCase
178Xfrom django.forms.models import modelform_factory
179Xfrom .models import DevicePciId, VendorPciId
180Xfrom datetime import datetime, tzinfo, timedelta
181X
182XPK_OUTPUT="""<select name="vendor" id="id_vendor">
183X<option value="">---------</option>
184X<option value="0x11ab" selected="selected">Marvell Technology Group
185XLtd.</option>
186X<option value="0xfeda">Broadcom Inc</option>
187X</select>"""
188X
189Xclass UTC(tzinfo) :
190X    def utcoffset(self, dt):
191X        return timedelta(0)
192X    def tzname(self, dt) :
193X        return "UTC"
194X    def dst(self, dt) :
195X        return timedelta(0)
196X
197Xutc = UTC()
198X
199Xclass SimpleTest(TestCase):
200X    def test_custom_field_as_pk(self) :
201X        now = datetime.utcnow().replace(tzinfo=utc)
202X        bc = VendorPciId.objects.create(identifier='0xfeda',
203X                name='Broadcom Inc', added=now)
204X        mtg = VendorPciId.objects.create(identifier='0x11ab',
205X                name='Marvell Technology Group Ltd.', added=now)
206X        msk = DevicePciId.objects.create(identifier='0x4363', vendor=mtg,
207X                name='88E8055 PCI-E Gigabit Ethernet Controller', added=now)
208X        form_class = modelform_factory(DevicePciId)
209X        form = form_class(instance=msk)
210X        output = unicode(form['vendor'])
211X        #print output
212X        self.assertHTMLEqual(output, PK_OUTPUT)
2135c6e7aac64209866496e51a471254275
214echo c - devices/fixtures
215mkdir -p devices/fixtures > /dev/null 2>&1
216echo x - devices/fixtures/msk.json
217sed 's/^X//' >devices/fixtures/msk.json << '399e6afc29059243ac06a621d3380c06'
218X[
219X{
220X  "pk": "0x11ab",
221X  "model": "devices.vendorpciid",
222X  "fields": {
223X    "added": "2012-07-17",
224X    "name": "Marvell Technology Group Ltd."
225X  }
226X},
227X{
228X  "pk": "0xfeda",
229X  "model": "devices.vendorpciid",
230X  "fields": {
231X    "added": "2012-07-17",
232X    "name": "Broadcom Inc"
233X  }
234X},
235X{
236X  "pk": 1,
237X  "model": "devices.devicepciid",
238X  "fields": {
239X    "identifier": "0x4363",
240X    "vendor": 4523,
241X    "name": "88E8055 PCI-E Gigabit Ethernet Controller",
242X    "added": "2012-07-17"
243X  }
244X}
245X]
246399e6afc29059243ac06a621d3380c06
247exit
248
Back to Top