(self)
| 247 | pack, format, x) |
| 248 | |
| 249 | def run(self): |
| 250 | from random import randrange |
| 251 | |
| 252 | # Create all interesting powers of 2. |
| 253 | values = [] |
| 254 | for exp in range(self.bitsize + 3): |
| 255 | values.append(1 << exp) |
| 256 | |
| 257 | # Add some random values. |
| 258 | for i in range(self.bitsize): |
| 259 | val = 0 |
| 260 | for j in range(self.bytesize): |
| 261 | val = (val << 8) | randrange(256) |
| 262 | values.append(val) |
| 263 | |
| 264 | # Values absorbed from other tests |
| 265 | values.extend([300, 700000, sys.maxsize*4]) |
| 266 | |
| 267 | # Try all those, and their negations, and +-1 from |
| 268 | # them. Note that this tests all power-of-2 |
| 269 | # boundaries in range, and a few out of range, plus |
| 270 | # +-(2**n +- 1). |
| 271 | for base in values: |
| 272 | for val in -base, base: |
| 273 | for incr in -1, 0, 1: |
| 274 | x = val + incr |
| 275 | self.test_one(x) |
| 276 | |
| 277 | # Some error cases. |
| 278 | class NotAnInt: |
| 279 | def __int__(self): |
| 280 | return 42 |
| 281 | |
| 282 | # Objects with an '__index__' method should be allowed |
| 283 | # to pack as integers. That is assuming the implemented |
| 284 | # '__index__' method returns an 'int'. |
| 285 | class Indexable(object): |
| 286 | def __init__(self, value): |
| 287 | self._value = value |
| 288 | |
| 289 | def __index__(self): |
| 290 | return self._value |
| 291 | |
| 292 | # If the '__index__' method raises a type error, then |
| 293 | # '__int__' should be used with a deprecation warning. |
| 294 | class BadIndex(object): |
| 295 | def __index__(self): |
| 296 | raise TypeError |
| 297 | |
| 298 | def __int__(self): |
| 299 | return 42 |
| 300 | |
| 301 | self.assertRaises((TypeError, struct.error), |
| 302 | struct.pack, self.format, |
| 303 | "a string") |
| 304 | self.assertRaises((TypeError, struct.error), |
| 305 | struct.pack, self.format, |
| 306 | randrange) |
no test coverage detected