How to use __class__ method in Slash

Best Python code snippet using slash

coordsys.py

Source:coordsys.py Github

copy

Full Screen

...35 return hash(self.coords)36 def __add__(self, other):37 if not isinstance(other, tuple):38 other = other.coords39 return self.__class__(40 tuple(self.coords[i] + other[i] for i in range(len(self.coords))))41 def __neg__(self):42 return self.__class__(43 tuple(-self.coords[i] for i in range(len(self.coords))))44 def __sub__(self, other):45 if not isinstance(other, tuple):46 other = other.coords47 return self.__class__(48 tuple(self.coords[i] - other[i] for i in range(len(self.coords))))49 def __cmp__(self, other):50 if isinstance(other, tuple):51 return cmp(self.coords, other)52 else:53 return cmp(self.coords, other.coords)54 def add_modulo(self, other, moduli):55 if not isinstance(other, tuple):56 other = other.coords57 return self.__class__(58 tuple((self.coords[i] + other[i]) % (modulus or sys.maxint)59 for i, modulus in enumerate(moduli)))60class CartesianCoordinates(CoordinateSystem):61 pass62class Cartesian1D(CartesianCoordinates):63 """1D coordinate system: (x)"""64 rotation_steps = None65 rotation_axes = None66 flippable = True67 def flip0(self):68 """Flip on last dimension, about origin"""69 return self.__class__(self.coords[:-1] + (-self.coords[-1],))70 def flip(self, pivot):71 """Flip about pivot"""72 temp = self - pivot73 return temp.flip0() + pivot74class Cartesian2D(Cartesian1D):75 """2D coordinate system: (x, y)"""76 rotation_steps = 477 rotation_axes = None78 flippable = True79 def rotate0(self, quadrants):80 """Rotate about (0,0)"""81 x = self.coords[quadrants % 2] * (-2 * ((quadrants + 1) // 2 % 2) + 1)82 y = self.coords[(quadrants + 1) % 2] * (-2 * (quadrants // 2 % 2) + 1)83 return self.__class__((x, y))84 def rotate(self, quadrants, pivot):85 """Rotate about pivot"""86 temp = self - pivot87 return temp.rotate0(quadrants) + pivot88 def neighbors(self):89 """Return a list of adjacent cells."""90 x, y = self.coords91 # counterclockwise from right92 return (self.__class__((x + 1, y)), # right93 self.__class__((x, y + 1)), # above94 self.__class__((x - 1, y)), # left95 self.__class__((x, y - 1))) # below96class Cartesian3D(Cartesian2D):97 """3D coordinate system: (x, y, z)"""98 rotation_steps = 499 rotation_axes = 3100 flippable = True101 def rotate0(self, quadrants, axis):102 """Rotate about (0,0,0); `axis` is 0/x, 1/y, 2/z."""103 rotated = Cartesian2D((self.coords[(axis + 1) % 3],104 self.coords[(axis + 2) % 3])).rotate0(quadrants)105 result = (self.coords[axis],) + tuple(rotated)106 return self.__class__(result[-axis:] + result[:-axis])107 def rotate(self, quadrants, axis, pivot):108 """Rotate about pivot"""109 temp = self - pivot110 return temp.rotate0(quadrants, axis) + pivot111 def flip0(self, axis):112 """Flip axis (180 degree rotation), about 0"""113 return self.rotate0(2, (axis + 1) % 3)114 def flip(self, axis, pivot):115 """Flip axis (180 degree rotation about next axis) about pivot"""116 temp = self - pivot117 return temp.flip0(axis) + pivot118 def neighbors(self):119 """Return a list of adjacent cells."""120 x, y, z = self.coords121 return (self.__class__((x + 1, y, z)), # right122 self.__class__((x - 1, y, z)), # left123 self.__class__((x, y + 1, z)), # above124 self.__class__((x, y - 1, z)), # below125 self.__class__((x, y, z + 1)), # in front126 self.__class__((x, y, z - 1))) # behind127class CoordinateSet(set):128 """Generic set of coordinates."""129 def __init__(self, coord_list):130 converted = [self.coord_class(c) for c in coord_list]131 self.update(converted)132 def rotate0(self, *args):133 return self.__class__([coord.rotate0(*args) for coord in self])134 def rotate(self, *args):135 return self.__class__([coord.rotate(*args) for coord in self])136 def flip0(self, *args):137 return self.__class__([coord.flip0(*args) for coord in self])138 def flip(self, *args):139 return self.__class__([coord.flip(*args) for coord in self])140 def translate(self, offset, moduli=None):141 """Move coordSet by offset"""142 new = self.__class__(list(self))143 new._itranslate(offset, moduli)144 return new145 def _itranslate(self, offset, moduli=None):146 """Move coordSet by offset, in place"""147 if isinstance(offset, tuple):148 offset = self.coord_class(offset)149 if moduli:150 newset = [coord.add_modulo(offset, moduli) for coord in self]151 else:152 newset = [coord + offset for coord in self]153 self.clear()154 self.update(newset)155class Cartesian1DCoordSet(CoordinateSet):156 """1 dimensional unit-cell coordinate set"""157 coord_class = Cartesian1D158class Cartesian2DCoordSet(CoordinateSet):159 """2 dimensional square-cell coordinate set"""160 coord_class = Cartesian2D161 def orient2D(self, rotation=0, flip=0):162 """163 Transform (rotate, flip) the coordinate set according to parameters.164 """165 if not (rotation == 0 and flip == 0):166 newSet = []167 for c in self:168 if flip:169 c = c.flip0()170 newSet.append(c.rotate0(rotation))171 self.clear()172 self.update(newSet)173class Cartesian3DCoordSet(CoordinateSet):174 """3 dimensional cube-cell coordinate set"""175 coord_class = Cartesian3D176 def orient3D(self, rotation=0, axis=0, flip=0):177 """178 Transform (rotate, flip) the coordinate set according to parameters.179 """180 if not (rotation == 0 and flip == 0):181 newSet = []182 for c in self:183 if flip:184 c = c.flip0((axis + 1) % 3)185 newSet.append(c.rotate0(rotation, axis))186 self.clear()187 self.update(newSet)188class Cartesian2DView(Cartesian2DCoordSet):189 """190 2 dimensional (+,+)-quadrant square-cell coordinate set with bounds191 """192 def __init__(self, coord_list, rotation=0, flip=0, axis=None):193 Cartesian2DCoordSet.__init__(self, coord_list)194 # transform self under aspect:195 self.orient2D(rotation, flip)196 offset, self.bounds = self.calculate_offset_and_bounds()197 # move coordSet to top-left at (0,0)198 self._itranslate(-offset)199 def __hash__(self):200 return hash(tuple(sorted(self)))201 def calculate_offset_and_bounds(self):202 rowvals = [c[0] for c in self]203 colvals = [c[1] for c in self]204 offset = self.coord_class((min(rowvals), min(colvals)))205 maxvals = self.coord_class((max(rowvals), max(colvals)))206 bounds = maxvals - offset207 return offset, bounds208class Cartesian3DView(Cartesian3DCoordSet):209 """210 3 dimensional (+,+,+)-quadrant square-cell coordinate set with bounds211 """212 def __init__(self, coord_list, rotation=0, axis=0, flip=0):213 Cartesian3DCoordSet.__init__(self, coord_list)214 # transform self under aspect:215 self.orient3D(rotation, axis, flip)216 offset, self.bounds = self.calculate_offset_and_bounds()217 # move coordSet to top-left at (0,0,0)218 self._itranslate(-offset)219 def __hash__(self):220 return hash(tuple(sorted(self)))221 def calculate_offset_and_bounds(self):222 rows = [c[0] for c in self]223 cols = [c[1] for c in self]224 layers = [c[2] for c in self]225 offset = self.coord_class((min(rows), min(cols), min(layers)))226 maxvals = self.coord_class((max(rows), max(cols), max(layers)))227 bounds = maxvals - offset228 return offset, bounds229class CartesianPseudo3DView(Cartesian3DView):230 """The Z dimension is used for direction/orientation."""231 def calculate_offset_and_bounds(self):232 rows = [c[0] for c in self]233 cols = [c[1] for c in self]234 layers = [c[2] for c in self]235 # keep Z-offset at 0 to keep Z values unaltered:236 offset = self.coord_class((min(rows), min(cols), 0))237 maxvals = self.coord_class((max(rows), max(cols), max(layers)))238 bounds = maxvals - offset239 return offset, bounds240class SquareGrid3D(Cartesian3D):241 """242 Pseudo-3D (2D + orientation) square coordinate system for gridlines: (x,243 y, z). The Z dimension is for orientation: z==0 for horizontal line244 segments (from (x,y) to (x+1,y)), and z==1 for vertical line segments245 (from (x,y) to (x,y+1)). The Z value indicates the index of the dimension246 to increment.247 """248 rotation_steps = 4249 rotation_axes = None250 flippable = True251 def flip0(self, axis=None):252 """253 Flip about y-axis::254 x_new = -x + z - 1255 y_new = y256 z_new = z257 The `axis` parameter is ignored.258 """259 return self.__class__(260 ((-self.coords[0] + self.coords[2] - 1),261 self.coords[1],262 self.coords[2]))263 rotation_coefficients = {264 0: (( 1, 0, 0, 0), ( 0, 1, 0, 0), ( 0, 0, 1, 0)),265 1: (( 0, -1, -1, 0), ( 1, 0, 0, 0), ( 0, 0, -1, 1)),266 2: ((-1, 0, 1, -1), ( 0, -1, -1, 0), ( 0, 0, 1, 0)),267 3: (( 0, 1, 0, 0), (-1, 0, 1, -1), ( 0, 0, -1, 1)),}268 """Pre-computed matrix for rotation by *n* 90-degree steps.269 Mapping of rotation unit (step) to coefficients matrix:270 ((x, y, z, 1) for x, (x, y, z, 1) for y, (x, y, z, 1) for z)."""271 def rotate0(self, steps, axis=None):272 """273 Rotate about (0,0). For each 90-degree increment (step)::274 x_new = -y - z275 y_new = x276 z_new = 1 - z277 The `self.rotation_coefficients` matrix is used rather than repeated278 applications of the above rule. The `axis` parameter is ignored.279 """280 coeffs = self.rotation_coefficients[steps]281 x = (coeffs[0][3]282 + coeffs[0][0] * self.coords[0]283 + coeffs[0][1] * self.coords[1]284 + coeffs[0][2] * self.coords[2])285 y = (coeffs[1][3]286 + coeffs[1][0] * self.coords[0]287 + coeffs[1][1] * self.coords[1]288 + coeffs[1][2] * self.coords[2])289 z = (coeffs[2][3]290 + coeffs[2][0] * self.coords[0]291 + coeffs[2][1] * self.coords[1]292 + coeffs[2][2] * self.coords[2])293 return self.__class__((x, y, z))294 def neighbors(self):295 """Return a list of adjacent cells."""296 x, y, z = self.coords297 # counterclockwise from right298 if z == 0:299 return (self.__class__((x + 1, y, 0)), # right, 1 right300 self.__class__((x + 1, y, 1)), # up, 1 right301 self.__class__((x, y, 1)), # up302 self.__class__((x - 1, y, 0)), # left303 self.__class__((x, y - 1, 1)), # down304 self.__class__((x + 1, y - 1, 1))) # down, 1 right305 else:306 return (self.__class__((x, y, 0)), # right307 self.__class__((x, y + 1, 0)), # right, 1 up308 self.__class__((x, y + 1, 1)), # up, 1 up309 self.__class__((x - 1, y + 1, 0)), # left, 1 up310 self.__class__((x - 1, y, 0)), # left311 self.__class__((x, y - 1, 1))) # down312class SquareGrid3DCoordSetMixin:313 """314 Attributes and methods for pseudo-3-dimensional square grid coordinate set.315 """316 coord_class = SquareGrid3D317 intersection_coord_class = Cartesian2D318 def intersections(self):319 coords = set()320 for (x,y,z) in self:321 if self.coord_class((x + (z == 0), y + (z == 1), z)) in self:322 coords.add(self.intersection_coord_class(323 (x + (z == 0), y + (z == 1))))324 return coords325class SquareGrid3DCoordSet(SquareGrid3DCoordSetMixin, Cartesian3DCoordSet):326 """Pseudo-3-dimensional square grid coordinate set."""327 pass328class SquareGrid3DView(SquareGrid3DCoordSetMixin, CartesianPseudo3DView):329 """330 Pseudo-3-dimensional (+x,+y)-quadrant square grid coordinate set with331 bounds332 """333 pass334class QuasiSquareGrid3D(SquareGrid3D):335 """336 Same as SquareGrid3D, except that calls to .neighbors() also return337 disconnected quasi-neighbors.338 """339 def neighbors(self):340 """Return a list of adjacent and quasi-adjacent cells."""341 adjacent = SquareGrid3D.neighbors(self)342 x, y, z = self.coords343 # counterclockwise from right344 if z == 0:345 return adjacent + (346 self.__class__((x , y + 1, 0)),347 self.__class__((x , y + 1, 1)),348 self.__class__((x - 1, y + 1, 0)),349 self.__class__((x - 1, y , 1)),350 self.__class__((x - 2, y , 0)),351 self.__class__((x - 1, y - 1, 1)),352 self.__class__((x - 1, y - 1, 0)),353 self.__class__((x , y - 2, 1)),354 self.__class__((x , y - 1, 0)),355 self.__class__((x + 1, y - 2, 1)),356 self.__class__((x + 1, y - 1, 0)),357 self.__class__((x + 2, y - 1, 1)),358 self.__class__((x + 2, y , 0)),359 self.__class__((x + 2, y , 1)),360 self.__class__((x + 1, y + 1, 0)),361 self.__class__((x + 1, y + 1, 1)),)362 else:363 return adjacent + (364 self.__class__((x - 1, y , 1)),365 self.__class__((x - 2, y , 0)),366 self.__class__((x - 1, y - 1, 1)),367 self.__class__((x - 1, y - 1, 0)),368 self.__class__((x , y - 2, 1)),369 self.__class__((x , y - 1, 0)),370 self.__class__((x + 1, y - 1, 1)),371 self.__class__((x + 1, y , 0)),372 self.__class__((x + 1, y , 1)),373 self.__class__((x + 1, y + 1, 0)),374 self.__class__((x + 1, y + 1, 1)),375 self.__class__((x , y + 2, 0)),376 self.__class__((x , y + 2, 1)),377 self.__class__((x - 1, y + 2, 0)),378 self.__class__((x - 1, y + 1, 1)),379 self.__class__((x - 2, y + 1, 0)),)380class QuasiSquareGrid3DCoordSet(SquareGrid3DCoordSet):381 coord_class = QuasiSquareGrid3D382class QuasiSquareGrid3DView(SquareGrid3DView):383 coord_class = QuasiSquareGrid3D384class Hexagonal2D(Cartesian2D):385 """386 2D hexagonal coordinate system: (x, y).387 The x and y axes are not perpendicular, but separated by 60 degrees::388 __389 __/ \390 __/ \__/391 __/ \__/ \392 __/ \__/ \__/393 / \__/ \__/ \394 4\__/ \__/ \__/395 / \__/ \__/ \396 3\__/ \__/ \__/397 / \__/ \__/ \398 2\__/ \__/ \__/399 / \__/ \__/ 4400 1\__/ \__/ 3401 / \__/ 2402 y=0\__/ 1403 x=0404 The x-axis could also be considered horizontal, with the y-axis slanted up405 and to the right, but the representation above is easier to draw in ASCII.406 """407 rotation_steps = 6408 rotation_axes = None409 flippable = True410 def flip0(self):411 """412 Flip about y-axis::413 x_new = -x414 y_new = x + y415 """416 return self.__class__((-self.coords[0],417 self.coords[1] + self.coords[0]))418 rotation_coefficients = {419 0: (( 1, 0), ( 0, 1)),420 1: (( 0, -1), ( 1, 1)),421 2: ((-1, -1), ( 1, 0)),422 3: ((-1, 0), ( 0, -1)),423 4: (( 0, 1), (-1, -1)),424 5: (( 1, 1), (-1, 0))}425 """Pre-computed matrix for rotation by *n* 60-degree steps.426 Mapping of rotation unit (step) to coefficients matrix:427 ((x, y) for x, (x, y) for y)."""428 def rotate0(self, steps):429 """430 Rotate about (0,0). For each 60-degree increment (step)::431 x_new = -y432 y_new = x + y433 The `self.rotation_coefficients` matrix is used rather than repeated434 applications of the above rule.435 """436 coeffs = self.rotation_coefficients[steps]437 x = coeffs[0][0] * self.coords[0] + coeffs[0][1] * self.coords[1]438 y = coeffs[1][0] * self.coords[0] + coeffs[1][1] * self.coords[1]439 return self.__class__((x, y))440 def neighbors(self):441 """Return a list of adjacent cells."""442 x, y = self.coords443 # counterclockwise from right444 return (self.__class__((x + 1, y)), # right445 self.__class__((x, y + 1)), # above-right446 self.__class__((x - 1, y + 1)), # above-left447 self.__class__((x - 1, y)), # left448 self.__class__((x, y - 1)), # below-left449 self.__class__((x + 1, y - 1))) # below-right450class Hexagonal2DCoordSet(Cartesian2DCoordSet):451 """2 dimensional hex coordinate set"""452 coord_class = Hexagonal2D453class Hexagonal2DView(Cartesian2DView):454 """455 2 dimensional (+,+)-quadrant hex-cell coordinate set with bounds456 """457 coord_class = Hexagonal2D458class Triangular3D(Cartesian3D):459 """460 Pseudo-3D (2D + orientation) triangular coordinate system: (x, y, z).461 The x and y axes are not perpendicular, but separated by 60 degrees::462 ____________________463 /\ /\ /\ /\ /\ /464 4/__\/__\/__\/__\/__\/465 /\ /\ /\ /\ /\ /466 3/__\/__\/__\/__\/__\/467 /\ /\ /\ /\ /\ /468 2/__\/__\/__\/__\/__\/469 /\ /\ /\ /\ /\ /470 1/__\/__\/__\/__\/__\/ ____471 /\ /\ /\ /\ /\ / /\ \ /472 y=0/__\/__\/__\/__\/__\/ z=0/__\ z=1\/473 x=0 1 2 3 4474 """475 rotation_steps = 6476 rotation_axes = None477 flippable = True478 def flip0(self, axis=None):479 """480 Flip about y-axis::481 x_new = -(x + y + z)482 y_new = y483 z_new = z484 The `axis` parameter is ignored.485 """486 return self.__class__(487 (-(self.coords[0] + self.coords[1] + self.coords[2]),488 self.coords[1],489 self.coords[2]))490 rotation_coefficients = {491 0: (( 1, 0, 0, 0), ( 0, 1, 0, 0), ( 0, 0, 1, 0)),492 1: (( 0, -1, 0, -1), ( 1, 1, 1, 0), ( 0, 0, -1, 1)),493 2: ((-1, -1, -1, -1), ( 1, 0, 0, 0), ( 0, 0, 1, 0)),494 3: ((-1, 0, 0, -1), ( 0, -1, 0, -1), ( 0, 0, -1, 1)),495 4: (( 0, 1, 0, 0), (-1, -1, -1, -1), ( 0, 0, 1, 0)),496 5: (( 1, 1, 1, 0), (-1, 0, 0, -1), ( 0, 0, -1, 1)),}497 """Pre-computed matrix for rotation by *n* 60-degree steps.498 Mapping of rotation unit (step) to coefficients matrix:499 ((x, y, z, 1) for x, (x, y, z, 1) for y, (x, y, z, 1) for z)."""500 def rotate0(self, steps, axis=None):501 """502 Rotate about (0,0). For each 60-degree increment (step)::503 x_new = -y - 1504 y_new = x + y + z505 z_new = 1 - z506 The `self.rotation_coefficients` matrix is used rather than repeated507 applications of the above rule. The `axis` parameter is ignored.508 """509 coeffs = self.rotation_coefficients[steps]510 x = (coeffs[0][3]511 + coeffs[0][0] * self.coords[0]512 + coeffs[0][1] * self.coords[1]513 + coeffs[0][2] * self.coords[2])514 y = (coeffs[1][3]515 + coeffs[1][0] * self.coords[0]516 + coeffs[1][1] * self.coords[1]517 + coeffs[1][2] * self.coords[2])518 z = (coeffs[2][3]519 + coeffs[2][0] * self.coords[0]520 + coeffs[2][1] * self.coords[1]521 + coeffs[2][2] * self.coords[2])522 return self.__class__((x, y, z))523 def neighbors(self):524 """Return a list of adjacent cells."""525 x, y, z = self.coords526 # counterclockwise from right527 if z == 0:528 return (self.__class__((x, y, 1)), # right529 self.__class__((x - 1, y, 1)), # left530 self.__class__((x, y - 1, 1))) # below531 else:532 return (self.__class__((x + 1, y, 0)), # right533 self.__class__((x, y + 1, 0)), # above534 self.__class__((x, y, 0))) # left535class Triangular3DCoordSet(Cartesian3DCoordSet):536 """Pseudo-3-dimensional triangular coordinate set."""537 coord_class = Triangular3D538class Triangular3DView(CartesianPseudo3DView):539 """540 Pseudo-3-dimensional (+x,+y)-quadrant triangle-cell coordinate set with541 bounds.542 """543 coord_class = Triangular3D544class TriangularGrid3D(Cartesian3D):545 """546 Pseudo-3D (2D + orientation) triangular coordinate system for gridlines:547 (x, y, z). The Z dimension is for orientation:548 == ========== ==============================549 z (x, y) to direction550 == ========== ==============================551 0 (x+1, y) 0°, horizontal, to the right552 1 (x, y+1) 60°, up & to the right553 2 (x-1, y+1) 120°, up & to the left554 == ========== ==============================555 Visually::556 z=2 z=1557 \ /558 \/___ z=0559 (x,y)560 """561 rotation_steps = 6562 rotation_axes = None563 flippable = True564 def flip0(self, axis=None):565 """566 Flip about y-axis::567 x1 = -x0568 y1 = x0 + y0569 z1 = 2 - z0570 The `axis` parameter is ignored.571 """572 return self.__class__(573 (-self.coords[0],574 self.coords[0] + self.coords[1],575 2 - self.coords[2]))576 def rotate0(self, steps, axis=None):577 """578 Rotate about (0,0). For each 60-degree increment (step)::579 x1 = -y0 - ((z0 + 1) // 3)580 y1 = x0 + y0581 z1 = (z0 + 1) % 3582 The `axis` parameter is ignored.583 """584 x1, y1, z1 = self.coords585 for i in range(steps):586 x0, y0, z0 = x1, y1, z1587 x1 = -y0 - int((z0 + 1) / 3)588 y1 = x0 + y0589 z1 = (z0 + 1) % 3590 return self.__class__((x1, y1, z1))591 def neighbors(self):592 """593 Return a list of adjacent cells, counterclockwise from segment, first594 around the origin point then around the endpoint.595 """596 x, y, z = self.coords597 if z == 0:598 return (self.__class__((x , y, 1)),599 self.__class__((x, y, 2)),600 self.__class__((x - 1, y, 0)),601 self.__class__((x, y - 1, 1)),602 self.__class__((x + 1, y - 1, 2)),603 self.__class__((x + 1, y - 1, 1)),604 self.__class__((x + 2, y - 1, 2)),605 self.__class__((x + 1, y, 0)),606 self.__class__((x + 1, y, 1)),607 self.__class__((x + 1, y, 2)))608 elif z == 1:609 return (self.__class__((x, y, 2)),610 self.__class__((x - 1, y, 0)),611 self.__class__((x, y - 1, 1)),612 self.__class__((x + 1, y - 1, 2)),613 self.__class__((x, y, 0)),614 self.__class__((x + 1, y, 2)),615 self.__class__((x, y + 1, 0)),616 self.__class__((x, y + 1, 1)),617 self.__class__((x, y + 1, 2)),618 self.__class__((x - 1, y + 1, 0)))619 elif z == 2:620 return (self.__class__((x - 1, y, 0)),621 self.__class__((x, y - 1, 1)),622 self.__class__((x + 1, y - 1, 2)),623 self.__class__((x, y, 0)),624 self.__class__((x, y, 1)),625 self.__class__((x - 1, y + 1, 0)),626 self.__class__((x - 1, y + 1, 1)),627 self.__class__((x - 1, y + 1, 2)),628 self.__class__((x - 2, y + 1, 0)),629 self.__class__((x - 1, y, 1)))630 endpoint_deltas = {631 0: (+1, 0), # 0°, horizontal, to the right632 1: ( 0, +1), # 60°, up & to the right633 2: (-1, +1)} # 120°, up & to the left634 def endpoint(self):635 """636 Return the coordinates of the endpoint of this segment, a segment637 sharing this segment's direction.638 """639 x, y, z = self.coords640 delta_x, delta_y = self.endpoint_deltas[z]641 return self.__class__((x + delta_x, y + delta_y, z))642 def intersection_coordinates(self):643 """644 Return a list of coordinates of the intersection segments of the645 start- and end-points of this coordinate.646 """647 intersections = []648 for coord in (self, self.endpoint()):649 x, y, z = coord650 intersections.extend(self.__class__((x, y, z)) for z in range(6))651 return intersections652 @classmethod653 def point_neighbors(cls, x, y):654 """655 Return a list of segments which adjoin point (x,y), in656 counterclockwise order from 0-degrees right.657 """658 return [cls(coords) for coords in (659 (x, y, 0), (x, y, 1), (x, y, 2),660 (x-1, y, 0), (x, y-1, 1), (x+1, y-1, 2))]661class TriangularGrid3DCoordSetMixin:662 """663 Attributes and methods for pseudo-3-dimensional triangular grid coordinate664 set.665 """666 coord_class = TriangularGrid3D667 intersection_coord_class = TriangularGrid3D668 def intersections(self):669 """670 Represent contstraints on intersections via up to 6 additional columns671 per intersection [*]_, in the form i(x,y,z) (or "x,y,zi"). The672 segment in direction "z" (below) cannot go through the intersection673 (x,y)::674 2 1675 \ /676 3___\/___0677 /\678 / \679 4 5680 .. [*] Possibly fewer columns for intersections at the edge of a681 puzzle shape. This represents an optimization.682 Note that since there are already 3 line segments originating at683 each intersection, the cost of intersection constraints is 2 per684 segment, which effectively multiplies the number of coordinate685 columns by 3.686 Starting at 0°, rotating counter-clockwise::687 B / A688 ____/___ D ____ E ____ F ____689 / \690 C / D' \691 * A: 60° (adjacent), no constraints.692 * B: 120° (one-gapper). 3 constraints: 2 legs {1,3}, plus gap {2}.693 * C: 180° (two-gapper). 4 constraints: 2 legs {3,0}, plus gaps {4,5}.694 * D: 240° (three-gapper), no constraints. However, D' is a one-gapper695 (= B).696 * E: 300° (four-gapper), no constraints.697 * F: 360° (five-gapper), no constraints.698 Both ends of each segment must be checked, but only counter-clockwise699 (to avoid duplication).700 """701 icoords = set()702 for coord in self:703 neighbors = coord.neighbors()704 x, y, z = coord705 # start of segment: check that ccw-adjacent segment not there:706 if neighbors[0] not in self:707 if neighbors[1] in self:708 icoords.add(self.intersection_coord_class((x, y, z)))709 icoords.add(710 self.intersection_coord_class((x, y, (z + 1) % 6)))711 icoords.add(712 self.intersection_coord_class((x, y, (z + 2) % 6)))713 elif neighbors[2] in self:714 icoords.add(self.intersection_coord_class((x, y, z)))715 icoords.add(716 self.intersection_coord_class((x, y, (z + 1) % 6)))717 icoords.add(718 self.intersection_coord_class((x, y, (z + 2) % 6)))719 icoords.add(720 self.intersection_coord_class((x, y, (z + 3) % 6)))721 # end of segment: check that ccw-adjacent segment not there:722 if neighbors[5] not in self:723 # origin of end of segment:724 xo, yo, zo = neighbors[7 - z]725 if neighbors[6] in self:726 icoords.add(self.intersection_coord_class((xo, yo, z + 3)))727 icoords.add(728 self.intersection_coord_class((xo, yo, (z + 4) % 6)))729 icoords.add(730 self.intersection_coord_class((xo, yo, (z + 5) % 6)))731 elif neighbors[7] in self:732 icoords.add(self.intersection_coord_class((xo, yo, z + 3)))733 icoords.add(734 self.intersection_coord_class((xo, yo, (z + 4) % 6)))735 icoords.add(736 self.intersection_coord_class((xo, yo, (z + 5) % 6)))737 icoords.add(738 self.intersection_coord_class((xo, yo, z)))739 return icoords740class TriangularGrid3DCoordSet(TriangularGrid3DCoordSetMixin,741 Cartesian3DCoordSet):742 """Pseudo-3-dimensional triangular grid coordinate set."""743 pass744class TriangularGrid3DView(TriangularGrid3DCoordSetMixin,745 CartesianPseudo3DView):746 """747 Pseudo-3-dimensional (+x,+y)-quadrant triangular grid coordinate set with748 bounds.749 """750 def calculate_offset_and_bounds(self):751 xs = [c[0] for c in self]752 # include x-coordinates of endpoints when z==2:753 xs.extend([c.endpoint()[0] for c in self if c[2] == 2])754 ys = [c[1] for c in self]755 zs = [c[2] for c in self]756 # keep Z-offset at 0 to keep Z values unaltered:757 offset = self.coord_class((min(xs), min(ys), 0))758 maxvals = self.coord_class((max(xs), max(ys), max(zs)))759 bounds = maxvals - offset760 return offset, bounds761class QuasiTriangularGrid3D(TriangularGrid3D):762 """763 Same as TriangularGrid3D, except that calls to .neighbors() also return764 disconnected quasi-neighbors.765 """766 def neighbors(self):767 """768 Return a list of adjacent cells, counterclockwise from segment, first769 around the origin point then around the endpoint.770 """771 adjacent = TriangularGrid3D.neighbors(self)772 x, y, z = self.coords773 if z == 0:774 return adjacent + (775 self.__class__((x , y + 1, 0)),776 self.__class__((x , y + 1, 1)),777 self.__class__((x , y + 1, 2)),778 self.__class__((x - 1, y + 1, 0)),779 self.__class__((x - 1, y + 1, 1)),780 self.__class__((x - 1, y + 1, 2)),781 self.__class__((x - 2, y + 1, 0)),782 self.__class__((x - 1, y , 1)),783 self.__class__((x - 1, y , 2)),784 self.__class__((x - 2, y , 0)),785 self.__class__((x - 1, y - 1, 1)),786 self.__class__((x , y - 1, 2)),787 self.__class__((x - 1, y - 1, 0)),788 self.__class__((x , y - 2, 1)),789 self.__class__((x + 1, y - 2, 2)),790 self.__class__((x , y - 1, 0)),791 self.__class__((x + 1, y - 2, 1)),792 self.__class__((x + 2, y - 2, 2)),793 self.__class__((x + 1, y - 1, 0)),794 self.__class__((x + 2, y - 2, 1)),795 self.__class__((x + 3, y - 2, 2)),796 self.__class__((x + 2, y - 1, 0)),797 self.__class__((x + 2, y - 1, 1)),798 self.__class__((x + 3, y - 1, 2)),799 self.__class__((x + 2, y , 0)),800 self.__class__((x + 2, y , 1)),801 self.__class__((x + 2, y , 2)),802 self.__class__((x + 1, y + 1, 0)),803 self.__class__((x + 1, y + 1, 1)),804 self.__class__((x + 1, y + 1, 2)),)805 elif z == 1:806 return adjacent + (807 self.__class__((x - 1, y + 1, 1)),808 self.__class__((x - 1, y + 1, 2)),809 self.__class__((x - 2, y + 1, 0)),810 self.__class__((x - 1, y , 1)),811 self.__class__((x - 1, y , 2)),812 self.__class__((x - 2, y , 0)),813 self.__class__((x - 1, y - 1, 1)),814 self.__class__((x , y - 1, 2)),815 self.__class__((x - 1, y - 1, 0)),816 self.__class__((x , y - 2, 1)),817 self.__class__((x + 1, y - 2, 2)),818 self.__class__((x , y - 1, 0)),819 self.__class__((x + 1, y - 2, 1)),820 self.__class__((x + 2, y - 2, 2)),821 self.__class__((x + 1, y - 1, 0)),822 self.__class__((x + 1, y - 1, 1)),823 self.__class__((x + 2, y - 1, 2)),824 self.__class__((x + 1, y , 0)),825 self.__class__((x + 1, y , 1)),826 self.__class__((x + 2, y , 2)),827 self.__class__((x + 1, y + 1, 0)),828 self.__class__((x + 1, y + 1, 1)),829 self.__class__((x + 1, y + 1, 2)),830 self.__class__((x , y + 2, 0)),831 self.__class__((x , y + 2, 1)),832 self.__class__((x , y + 2, 2)),833 self.__class__((x - 1, y + 2, 0)),834 self.__class__((x - 1, y + 2, 1)),835 self.__class__((x - 1, y + 2, 2)),836 self.__class__((x - 2, y + 2, 0)),)837 elif z == 2:838 return adjacent + (839 self.__class__((x - 1, y , 2)),840 self.__class__((x - 2, y , 0)),841 self.__class__((x - 1, y - 1, 1)),842 self.__class__((x , y - 1, 2)),843 self.__class__((x - 1, y - 1, 0)),844 self.__class__((x , y - 2, 1)),845 self.__class__((x + 1, y - 2, 2)),846 self.__class__((x , y - 1, 0)),847 self.__class__((x + 1, y - 2, 1)),848 self.__class__((x + 2, y - 2, 2)),849 self.__class__((x + 1, y - 1, 0)),850 self.__class__((x + 1, y - 1, 1)),851 self.__class__((x + 2, y - 1, 2)),852 self.__class__((x + 1, y , 0)),853 self.__class__((x + 1, y , 1)),854 self.__class__((x + 1, y , 2)),855 self.__class__((x , y + 1, 0)),856 self.__class__((x , y + 1, 1)),857 self.__class__((x , y + 1, 2)),858 self.__class__((x - 1, y + 2, 0)),859 self.__class__((x - 1, y + 2, 1)),860 self.__class__((x - 1, y + 2, 2)),861 self.__class__((x - 2, y + 2, 0)),862 self.__class__((x - 2, y + 2, 1)),863 self.__class__((x - 2, y + 2, 2)),864 self.__class__((x - 3, y + 2, 0)),865 self.__class__((x - 2, y + 1, 1)),866 self.__class__((x - 2, y + 1, 2)),867 self.__class__((x - 3, y + 1, 0)),868 self.__class__((x - 2, y , 1)),)869class QuasiTriangularGrid3DCoordSet(TriangularGrid3DCoordSet):870 coord_class = QuasiTriangularGrid3D871class QuasiTriangularGrid3DView(TriangularGrid3DView):872 coord_class = QuasiTriangularGrid3D873class HexagonalGrid3D(Cartesian3D):874 """875 Pseudo-3D (2D + orientation) hexagonal coordinate system for gridlines:876 (x, y, z). (x, y) = lower-left corner of (x, y) hexagon in polyhex grid.877 The Z dimension is for orientation:878 == ========== ==============================879 z (x, y) to direction880 == ========== ==============================881 0 (x+1, y) 0°, horizontal, to the right882 1 (x, y+1) 120°, up & to the left883 2 (x-1, y) 240°, down & to the left884 == ========== ==============================885 Visually::886 z=1887 \888 \____z=0889 /890 /891 z=2892 """893 rotation_steps = 6894 rotation_axes = None895 flippable = True896 def flip0(self, axis=None):897 """898 Flip about y-axis (stack of hexes above origin)::899 == ====== ========= ========900 z x' = y' = z' =901 == ====== ========= ========902 0 -x x + y (-z) % 3903 1 -x + 1 '' ''904 2 '' x + y - 1 ''905 == ====== ========= ========906 The `axis` parameter is ignored.907 """908 x, y, z = self.coords909 x1 = -x + (z != 0)910 y1 = x + y - (z == 2)911 z1 = (-z) % 3912 return self.__class__((x1, y1, z1))913 def rotate0(self, steps, axis=None):914 """915 Rotate about (0,0). For each 60-degree increment (step)::916 == ====== ========= ===========917 z x' = y' = z' =918 == ====== ========= ===========919 0 -y + 1 x + y (z - 1) % 3920 1 -y '' ''921 2 -y + 1 x + y - 1 ''922 == ====== ========= ===========923 The `axis` parameter is ignored.924 """925 x1, y1, z1 = self.coords926 for i in range(steps):927 x0, y0, z0 = x1, y1, z1928 x1 = -y0 + (z0 != 1)929 y1 = x0 + y0 - (z0 == 2)930 z1 = (z0 - 1) % 3931 return self.__class__((x1, y1, z1))932 def neighbors(self):933 """934 Return a list of adjacent cells, counterclockwise from segment, first935 around the origin point then around the endpoint.936 """937 x, y, z = self.coords938 if z == 0:939 return (self.__class__((x , y, 1)),940 self.__class__((x, y, 2)),941 self.__class__((x + 1, y - 1, 1)),942 self.__class__((x + 1, y, 2)))943 elif z == 1:944 return (self.__class__((x, y, 2)),945 self.__class__((x, y, 0)),946 self.__class__((x, y + 1, 2)),947 self.__class__((x - 1, y + 1, 0)))948 elif z == 2:949 return (self.__class__((x, y, 0)),950 self.__class__((x, y, 1)),951 self.__class__((x - 1, y, 0)),952 self.__class__((x, y - 1, 1)))953class HexagonalGrid3DCoordSet(Cartesian3DCoordSet):954 """Pseudo-3-dimensional hexagonal grid coordinate set."""955 coord_class = HexagonalGrid3D956class HexagonalGrid3DView(CartesianPseudo3DView):957 """958 Pseudo-3-dimensional (+x,+y)-quadrant hexagonal grid coordinate set with959 bounds.960 """961 coord_class = HexagonalGrid3D962 def calculate_offset_and_bounds(self):963 xs = [c[0] for c in self]964 ys = [c[1] for c in self]965 zs = [c[2] for c in self]966 # keep Z-offset at 0 to keep Z values unaltered:967 offset = self.coord_class((min(xs), min(ys), 0))968 maxvals = self.coord_class((max(xs), max(ys), max(zs)))969 bounds = maxvals - offset970 return offset, bounds971class QuasiHexagonalGrid3D(HexagonalGrid3D):972 """973 Same as HexagonalGrid3D, except that calls to .neighbors() also return974 disconnected quasi-neighbors.975 """976 def neighbors(self):977 """978 Return a list of adjacent and quasi-adjacent cells, counterclockwise979 from segment, first around the origin point then around the endpoint.980 """981 adjacent = HexagonalGrid3D.neighbors(self)982 x, y, z = self.coords983 if z == 0:984 return adjacent + (985 self.__class__((x , y + 1, 2)),986 self.__class__((x - 1, y + 1, 0)),987 self.__class__((x - 1, y , 0)),988 self.__class__((x , y - 1, 1)),989 self.__class__((x + 1, y - 1, 2)),990 self.__class__((x + 1, y - 1, 0)),991 self.__class__((x + 1, y , 0)),992 self.__class__((x + 1, y , 1)),)993 elif z == 1:994 return adjacent + (995 self.__class__((x - 1, y , 0)),996 self.__class__((x , y - 1, 1)),997 self.__class__((x + 1, y - 1, 1)),998 self.__class__((x + 1, y , 2)),999 self.__class__((x , y + 1, 0)),1000 self.__class__((x , y + 1, 1)),1001 self.__class__((x - 1, y + 1, 1)),1002 self.__class__((x - 1, y + 1, 2)),)1003 elif z == 2:1004 return adjacent + (1005 self.__class__((x + 1, y - 1, 1)),1006 self.__class__((x + 1, y , 2)),1007 self.__class__((x , y + 1, 2)),1008 self.__class__((x - 1, y + 1, 0)),1009 self.__class__((x - 1, y , 1)),1010 self.__class__((x - 1, y , 2)),1011 self.__class__((x , y - 1, 2)),1012 self.__class__((x , y - 1, 0)),)1013class QuasiHexagonalGrid3DCoordSet(HexagonalGrid3DCoordSet):1014 coord_class = QuasiHexagonalGrid3D1015class QuasiHexagonalGrid3DView(HexagonalGrid3DView):1016 coord_class = QuasiHexagonalGrid3D1017def sign(num):1018 return cmp(num, 0)1019def increment_2D(start, end):1020 """1021 Given a `start`- and `end`-point which differ in only one dimension,1022 return a unit vector increment which if repeatedly added to the1023 start-point will eventually result in the end-point.1024 """...

Full Screen

Full Screen

placement_service_unittest.py

Source:placement_service_unittest.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: UTF-8 -*-3#4# Copyright 2011 Google Inc. All Rights Reserved.5#6# Licensed under the Apache License, Version 2.0 (the "License");7# you may not use this file except in compliance with the License.8# You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing, software13# distributed under the License is distributed on an "AS IS" BASIS,14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15# See the License for the specific language governing permissions and16# limitations under the License.17"""Unit tests to cover PlacementService."""18__author__ = 'api.sgrinberg@gmail.com (Stan Grinberg)'19import os20import sys21sys.path.append(os.path.join('..', '..', '..'))22import unittest23from adspygoogle.common import Utils24from tests.adspygoogle.dfp import HTTP_PROXY25from tests.adspygoogle.dfp import SERVER_V20100426from tests.adspygoogle.dfp import SERVER_V20101027from tests.adspygoogle.dfp import SERVER_V20110128from tests.adspygoogle.dfp import SERVER_V20110329from tests.adspygoogle.dfp import VERSION_V20100430from tests.adspygoogle.dfp import VERSION_V20101031from tests.adspygoogle.dfp import VERSION_V20110132from tests.adspygoogle.dfp import VERSION_V20110333from tests.adspygoogle.dfp import client34class PlacementServiceTestV201004(unittest.TestCase):35 """Unittest suite for PlacementService using v201004."""36 SERVER = SERVER_V20100437 VERSION = VERSION_V20100438 client.debug = False39 service = None40 ad_unit_id1 = '0'41 ad_unit_id2 = '0'42 ad_unit_id3 = '0'43 ad_unit_id4 = '0'44 placement1 = None45 placement2 = None46 def setUp(self):47 """Prepare unittest."""48 print self.id()49 if not self.__class__.service:50 self.__class__.service = client.GetPlacementService(51 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)52 if self.__class__.ad_unit_id1 == '0' or self.__class__.ad_unit_id2 == '0':53 inventory_service = client.GetInventoryService(54 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)55 network_service = client.GetNetworkService(56 self.__class__.SERVER, self.__class__.VERSION,57 HTTP_PROXY)58 root_ad_unit_id = \59 network_service.GetCurrentNetwork()[0]['effectiveRootAdUnitId']60 ad_units = [61 {62 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),63 'parentId': root_ad_unit_id,64 'sizes': [{'width': '300', 'height': '250'}]65 },66 {67 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),68 'parentId': root_ad_unit_id,69 'sizes': [{'width': '300', 'height': '250'}]70 },71 {72 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),73 'parentId': root_ad_unit_id,74 'sizes': [{'width': '300', 'height': '250'}]75 },76 {77 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),78 'parentId': root_ad_unit_id,79 'sizes': [{'width': '300', 'height': '250'}]80 }81 ]82 ad_units = inventory_service.CreateAdUnits(ad_units)83 self.__class__.ad_unit_id1 = ad_units[0]['id']84 self.__class__.ad_unit_id2 = ad_units[1]['id']85 self.__class__.ad_unit_id3 = ad_units[2]['id']86 self.__class__.ad_unit_id4 = ad_units[3]['id']87 def testCreatePlacement(self):88 """Test whether we can create a placement."""89 placement = {90 'name': 'Placement #%s' % Utils.GetUniqueName(),91 'description': 'Description.',92 'targetedAdUnitIds': [self.__class__.ad_unit_id1,93 self.__class__.ad_unit_id2]94 }95 self.assert_(isinstance(96 self.__class__.service.CreatePlacement(placement), tuple))97 def testCreatePlacements(self):98 """Test whether we can create a list of placements items."""99 placements = [100 {101 'name': 'Placement #%s' % Utils.GetUniqueName(),102 'description': 'Description.',103 'targetedAdUnitIds': [self.__class__.ad_unit_id1,104 self.__class__.ad_unit_id2]105 },106 {107 'name': 'Placement #%s' % Utils.GetUniqueName(),108 'description': 'Description.',109 'targetedAdUnitIds': [self.__class__.ad_unit_id1,110 self.__class__.ad_unit_id2]111 }112 ]113 placements = self.__class__.service.CreatePlacements(placements)114 self.assert_(isinstance(placements, tuple))115 self.__class__.placement1 = placements[0]116 self.__class__.placement2 = placements[1]117 def testGetPlacement(self):118 """Test whether we can fetch an existing placement."""119 if not self.__class__.placement1:120 self.testCreatePlacements()121 self.assert_(isinstance(self.__class__.service.GetPlacement(122 self.__class__.placement1['id']), tuple))123 def testGetPlacementsByStatement(self):124 """Test whether we can fetch a list of existing placements that match given125 statement."""126 if not self.__class__.placement1:127 self.testCreatePlacements()128 filter_statement = {'query': 'WHERE id = \'%s\' ORDER BY name LIMIT 1'129 % self.__class__.placement1['id']}130 self.assert_(isinstance(131 self.__class__.service.GetPlacementsByStatement(filter_statement),132 tuple))133 def testPerformPlacementAction(self):134 """Test whether we can deactivate a placement."""135 if not self.__class__.placement1:136 self.testCreatePlacements()137 action = {'type': 'DeactivatePlacements'}138 filter_statement = {'query': 'WHERE status = \'ACTIVE\''}139 self.assert_(isinstance(140 self.__class__.service.PerformPlacementAction(action, filter_statement),141 tuple))142 def testUpdatePlacement(self):143 """Test whether we can update a placement."""144 if not self.__class__.placement1:145 self.testCreatePlacements()146 self.__class__.placement1['description'] += ' More description.'147 placement = self.__class__.service.UpdatePlacement(148 self.__class__.placement1)149 self.assert_(isinstance(placement, tuple))150 self.assertEqual(placement[0]['description'],151 self.__class__.placement1['description'])152 self.__class__.placement1['targetedAdUnitIds'].append(153 self.__class__.ad_unit_id3)154 placement = self.__class__.service.UpdatePlacement(155 self.__class__.placement1)156 self.assert_(isinstance(placement, tuple))157 def testUpdatePlacements(self):158 """Test whether we can update a list of placements."""159 if not self.__class__.placement1 or not self.__class__.placement2:160 self.testCreatePlacements()161 self.__class__.placement1['description'] += ' Even more description.'162 self.__class__.placement2['description'] += ' Even more description.'163 placements = self.__class__.service.UpdatePlacements([164 self.__class__.placement1, self.__class__.placement2])165 self.assert_(isinstance(placements, tuple))166 self.__class__.placement1['targetedAdUnitIds'].append(167 self.__class__.ad_unit_id4)168 self.__class__.placement2['targetedAdUnitIds'].append(169 self.__class__.ad_unit_id4)170 placements = self.__class__.service.UpdatePlacements([171 self.__class__.placement1, self.__class__.placement2])172 self.assert_(isinstance(placements, tuple))173class PlacementServiceTestV201010(unittest.TestCase):174 """Unittest suite for PlacementService using v201010."""175 SERVER = SERVER_V201010176 VERSION = VERSION_V201010177 client.debug = False178 service = None179 ad_unit_id1 = '0'180 ad_unit_id2 = '0'181 ad_unit_id3 = '0'182 ad_unit_id4 = '0'183 placement1 = None184 placement2 = None185 def setUp(self):186 """Prepare unittest."""187 print self.id()188 if not self.__class__.service:189 self.__class__.service = client.GetPlacementService(190 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)191 if self.__class__.ad_unit_id1 == '0' or self.__class__.ad_unit_id2 == '0':192 inventory_service = client.GetInventoryService(193 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)194 network_service = client.GetNetworkService(195 self.__class__.SERVER, self.__class__.VERSION,196 HTTP_PROXY)197 root_ad_unit_id = \198 network_service.GetCurrentNetwork()[0]['effectiveRootAdUnitId']199 ad_units = [200 {201 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),202 'parentId': root_ad_unit_id,203 'sizes': [{'width': '300', 'height': '250'}]204 },205 {206 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),207 'parentId': root_ad_unit_id,208 'sizes': [{'width': '300', 'height': '250'}]209 },210 {211 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),212 'parentId': root_ad_unit_id,213 'sizes': [{'width': '300', 'height': '250'}]214 },215 {216 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),217 'parentId': root_ad_unit_id,218 'sizes': [{'width': '300', 'height': '250'}]219 }220 ]221 ad_units = inventory_service.CreateAdUnits(ad_units)222 self.__class__.ad_unit_id1 = ad_units[0]['id']223 self.__class__.ad_unit_id2 = ad_units[1]['id']224 self.__class__.ad_unit_id3 = ad_units[2]['id']225 self.__class__.ad_unit_id4 = ad_units[3]['id']226 def testCreatePlacement(self):227 """Test whether we can create a placement."""228 placement = {229 'name': 'Placement #%s' % Utils.GetUniqueName(),230 'description': 'Description.',231 'targetedAdUnitIds': [self.__class__.ad_unit_id1,232 self.__class__.ad_unit_id2]233 }234 self.assert_(isinstance(235 self.__class__.service.CreatePlacement(placement), tuple))236 def testCreatePlacements(self):237 """Test whether we can create a list of placements items."""238 placements = [239 {240 'name': 'Placement #%s' % Utils.GetUniqueName(),241 'description': 'Description.',242 'targetedAdUnitIds': [self.__class__.ad_unit_id1,243 self.__class__.ad_unit_id2]244 },245 {246 'name': 'Placement #%s' % Utils.GetUniqueName(),247 'description': 'Description.',248 'targetedAdUnitIds': [self.__class__.ad_unit_id1,249 self.__class__.ad_unit_id2]250 }251 ]252 placements = self.__class__.service.CreatePlacements(placements)253 self.assert_(isinstance(placements, tuple))254 self.__class__.placement1 = placements[0]255 self.__class__.placement2 = placements[1]256 def testGetPlacement(self):257 """Test whether we can fetch an existing placement."""258 if not self.__class__.placement1:259 self.testCreatePlacements()260 self.assert_(isinstance(self.__class__.service.GetPlacement(261 self.__class__.placement1['id']), tuple))262 def testGetPlacementsByStatement(self):263 """Test whether we can fetch a list of existing placements that match given264 statement."""265 if not self.__class__.placement1:266 self.testCreatePlacements()267 filter_statement = {'query': 'WHERE id = \'%s\' ORDER BY name LIMIT 1'268 % self.__class__.placement1['id']}269 self.assert_(isinstance(270 self.__class__.service.GetPlacementsByStatement(filter_statement),271 tuple))272 def testPerformPlacementAction(self):273 """Test whether we can deactivate a placement."""274 if not self.__class__.placement1:275 self.testCreatePlacements()276 action = {'type': 'DeactivatePlacements'}277 filter_statement = {'query': 'WHERE status = \'ACTIVE\''}278 self.assert_(isinstance(279 self.__class__.service.PerformPlacementAction(action, filter_statement),280 tuple))281 def testUpdatePlacement(self):282 """Test whether we can update a placement."""283 if not self.__class__.placement1:284 self.testCreatePlacements()285 self.__class__.placement1['description'] += ' More description.'286 placement = self.__class__.service.UpdatePlacement(287 self.__class__.placement1)288 self.assert_(isinstance(placement, tuple))289 self.assertEqual(placement[0]['description'],290 self.__class__.placement1['description'])291 self.__class__.placement1['targetedAdUnitIds'].append(292 self.__class__.ad_unit_id3)293 placement = self.__class__.service.UpdatePlacement(294 self.__class__.placement1)295 self.assert_(isinstance(placement, tuple))296 def testUpdatePlacements(self):297 """Test whether we can update a list of placements."""298 if not self.__class__.placement1 or not self.__class__.placement2:299 self.testCreatePlacements()300 self.__class__.placement1['description'] += ' Even more description.'301 self.__class__.placement2['description'] += ' Even more description.'302 placements = self.__class__.service.UpdatePlacements([303 self.__class__.placement1, self.__class__.placement2])304 self.assert_(isinstance(placements, tuple))305 self.__class__.placement1['targetedAdUnitIds'].append(306 self.__class__.ad_unit_id4)307 self.__class__.placement2['targetedAdUnitIds'].append(308 self.__class__.ad_unit_id4)309 placements = self.__class__.service.UpdatePlacements([310 self.__class__.placement1, self.__class__.placement2])311 self.assert_(isinstance(placements, tuple))312class PlacementServiceTestV201101(unittest.TestCase):313 """Unittest suite for PlacementService using v201101."""314 SERVER = SERVER_V201101315 VERSION = VERSION_V201101316 client.debug = False317 service = None318 ad_unit_id1 = '0'319 ad_unit_id2 = '0'320 ad_unit_id3 = '0'321 ad_unit_id4 = '0'322 placement1 = None323 placement2 = None324 def setUp(self):325 """Prepare unittest."""326 print self.id()327 if not self.__class__.service:328 self.__class__.service = client.GetPlacementService(329 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)330 if self.__class__.ad_unit_id1 == '0' or self.__class__.ad_unit_id2 == '0':331 inventory_service = client.GetInventoryService(332 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)333 network_service = client.GetNetworkService(334 self.__class__.SERVER, self.__class__.VERSION,335 HTTP_PROXY)336 root_ad_unit_id = \337 network_service.GetCurrentNetwork()[0]['effectiveRootAdUnitId']338 ad_units = [339 {340 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),341 'parentId': root_ad_unit_id,342 'sizes': [{'width': '300', 'height': '250'}]343 },344 {345 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),346 'parentId': root_ad_unit_id,347 'sizes': [{'width': '300', 'height': '250'}]348 },349 {350 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),351 'parentId': root_ad_unit_id,352 'sizes': [{'width': '300', 'height': '250'}]353 },354 {355 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),356 'parentId': root_ad_unit_id,357 'sizes': [{'width': '300', 'height': '250'}]358 }359 ]360 ad_units = inventory_service.CreateAdUnits(ad_units)361 self.__class__.ad_unit_id1 = ad_units[0]['id']362 self.__class__.ad_unit_id2 = ad_units[1]['id']363 self.__class__.ad_unit_id3 = ad_units[2]['id']364 self.__class__.ad_unit_id4 = ad_units[3]['id']365 def testCreatePlacement(self):366 """Test whether we can create a placement."""367 placement = {368 'name': 'Placement #%s' % Utils.GetUniqueName(),369 'description': 'Description.',370 'targetedAdUnitIds': [self.__class__.ad_unit_id1,371 self.__class__.ad_unit_id2]372 }373 self.assert_(isinstance(374 self.__class__.service.CreatePlacement(placement), tuple))375 def testCreatePlacements(self):376 """Test whether we can create a list of placements items."""377 placements = [378 {379 'name': 'Placement #%s' % Utils.GetUniqueName(),380 'description': 'Description.',381 'targetedAdUnitIds': [self.__class__.ad_unit_id1,382 self.__class__.ad_unit_id2]383 },384 {385 'name': 'Placement #%s' % Utils.GetUniqueName(),386 'description': 'Description.',387 'targetedAdUnitIds': [self.__class__.ad_unit_id1,388 self.__class__.ad_unit_id2]389 }390 ]391 placements = self.__class__.service.CreatePlacements(placements)392 self.assert_(isinstance(placements, tuple))393 self.__class__.placement1 = placements[0]394 self.__class__.placement2 = placements[1]395 def testGetPlacement(self):396 """Test whether we can fetch an existing placement."""397 if not self.__class__.placement1:398 self.testCreatePlacements()399 self.assert_(isinstance(self.__class__.service.GetPlacement(400 self.__class__.placement1['id']), tuple))401 def testGetPlacementsByStatement(self):402 """Test whether we can fetch a list of existing placements that match given403 statement."""404 if not self.__class__.placement1:405 self.testCreatePlacements()406 filter_statement = {'query': 'WHERE id = \'%s\' ORDER BY name LIMIT 1'407 % self.__class__.placement1['id']}408 self.assert_(isinstance(409 self.__class__.service.GetPlacementsByStatement(filter_statement),410 tuple))411 def testPerformPlacementAction(self):412 """Test whether we can deactivate a placement."""413 if not self.__class__.placement1:414 self.testCreatePlacements()415 action = {'type': 'DeactivatePlacements'}416 filter_statement = {'query': 'WHERE status = \'ACTIVE\''}417 self.assert_(isinstance(418 self.__class__.service.PerformPlacementAction(action, filter_statement),419 tuple))420 def testUpdatePlacement(self):421 """Test whether we can update a placement."""422 if not self.__class__.placement1:423 self.testCreatePlacements()424 self.__class__.placement1['description'] += ' More description.'425 placement = self.__class__.service.UpdatePlacement(426 self.__class__.placement1)427 self.assert_(isinstance(placement, tuple))428 self.assertEqual(placement[0]['description'],429 self.__class__.placement1['description'])430 self.__class__.placement1['targetedAdUnitIds'].append(431 self.__class__.ad_unit_id3)432 placement = self.__class__.service.UpdatePlacement(433 self.__class__.placement1)434 self.assert_(isinstance(placement, tuple))435 def testUpdatePlacements(self):436 """Test whether we can update a list of placements."""437 if not self.__class__.placement1 or not self.__class__.placement2:438 self.testCreatePlacements()439 self.__class__.placement1['description'] += ' Even more description.'440 self.__class__.placement2['description'] += ' Even more description.'441 placements = self.__class__.service.UpdatePlacements([442 self.__class__.placement1, self.__class__.placement2])443 self.assert_(isinstance(placements, tuple))444 self.__class__.placement1['targetedAdUnitIds'].append(445 self.__class__.ad_unit_id4)446 self.__class__.placement2['targetedAdUnitIds'].append(447 self.__class__.ad_unit_id4)448 placements = self.__class__.service.UpdatePlacements([449 self.__class__.placement1, self.__class__.placement2])450 self.assert_(isinstance(placements, tuple))451class PlacementServiceTestV201103(unittest.TestCase):452 """Unittest suite for PlacementService using v201103."""453 SERVER = SERVER_V201103454 VERSION = VERSION_V201103455 client.debug = False456 service = None457 ad_unit_id1 = '0'458 ad_unit_id2 = '0'459 ad_unit_id3 = '0'460 ad_unit_id4 = '0'461 placement1 = None462 placement2 = None463 def setUp(self):464 """Prepare unittest."""465 print self.id()466 if not self.__class__.service:467 self.__class__.service = client.GetPlacementService(468 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)469 if self.__class__.ad_unit_id1 == '0' or self.__class__.ad_unit_id2 == '0':470 inventory_service = client.GetInventoryService(471 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)472 network_service = client.GetNetworkService(473 self.__class__.SERVER, self.__class__.VERSION,474 HTTP_PROXY)475 root_ad_unit_id = \476 network_service.GetCurrentNetwork()[0]['effectiveRootAdUnitId']477 ad_units = [478 {479 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),480 'parentId': root_ad_unit_id,481 'sizes': [{'width': '300', 'height': '250'}]482 },483 {484 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),485 'parentId': root_ad_unit_id,486 'sizes': [{'width': '300', 'height': '250'}]487 },488 {489 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),490 'parentId': root_ad_unit_id,491 'sizes': [{'width': '300', 'height': '250'}]492 },493 {494 'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),495 'parentId': root_ad_unit_id,496 'sizes': [{'width': '300', 'height': '250'}]497 }498 ]499 ad_units = inventory_service.CreateAdUnits(ad_units)500 self.__class__.ad_unit_id1 = ad_units[0]['id']501 self.__class__.ad_unit_id2 = ad_units[1]['id']502 self.__class__.ad_unit_id3 = ad_units[2]['id']503 self.__class__.ad_unit_id4 = ad_units[3]['id']504 def testCreatePlacement(self):505 """Test whether we can create a placement."""506 placement = {507 'name': 'Placement #%s' % Utils.GetUniqueName(),508 'description': 'Description.',509 'targetedAdUnitIds': [self.__class__.ad_unit_id1,510 self.__class__.ad_unit_id2]511 }512 self.assert_(isinstance(513 self.__class__.service.CreatePlacement(placement), tuple))514 def testCreatePlacements(self):515 """Test whether we can create a list of placements items."""516 placements = [517 {518 'name': 'Placement #%s' % Utils.GetUniqueName(),519 'description': 'Description.',520 'targetedAdUnitIds': [self.__class__.ad_unit_id1,521 self.__class__.ad_unit_id2]522 },523 {524 'name': 'Placement #%s' % Utils.GetUniqueName(),525 'description': 'Description.',526 'targetedAdUnitIds': [self.__class__.ad_unit_id1,527 self.__class__.ad_unit_id2]528 }529 ]530 placements = self.__class__.service.CreatePlacements(placements)531 self.assert_(isinstance(placements, tuple))532 self.__class__.placement1 = placements[0]533 self.__class__.placement2 = placements[1]534 def testGetPlacement(self):535 """Test whether we can fetch an existing placement."""536 if not self.__class__.placement1:537 self.testCreatePlacements()538 self.assert_(isinstance(self.__class__.service.GetPlacement(539 self.__class__.placement1['id']), tuple))540 def testGetPlacementsByStatement(self):541 """Test whether we can fetch a list of existing placements that match given542 statement."""543 if not self.__class__.placement1:544 self.testCreatePlacements()545 filter_statement = {'query': 'WHERE id = \'%s\' ORDER BY name LIMIT 1'546 % self.__class__.placement1['id']}547 self.assert_(isinstance(548 self.__class__.service.GetPlacementsByStatement(filter_statement),549 tuple))550 def testPerformPlacementAction(self):551 """Test whether we can deactivate a placement."""552 if not self.__class__.placement1:553 self.testCreatePlacements()554 action = {'type': 'DeactivatePlacements'}555 filter_statement = {'query': 'WHERE status = \'ACTIVE\''}556 self.assert_(isinstance(557 self.__class__.service.PerformPlacementAction(action, filter_statement),558 tuple))559 def testUpdatePlacement(self):560 """Test whether we can update a placement."""561 if not self.__class__.placement1:562 self.testCreatePlacements()563 self.__class__.placement1['description'] += ' More description.'564 placement = self.__class__.service.UpdatePlacement(565 self.__class__.placement1)566 self.assert_(isinstance(placement, tuple))567 self.assertEqual(placement[0]['description'],568 self.__class__.placement1['description'])569 self.__class__.placement1['targetedAdUnitIds'].append(570 self.__class__.ad_unit_id3)571 placement = self.__class__.service.UpdatePlacement(572 self.__class__.placement1)573 self.assert_(isinstance(placement, tuple))574 def testUpdatePlacements(self):575 """Test whether we can update a list of placements."""576 if not self.__class__.placement1 or not self.__class__.placement2:577 self.testCreatePlacements()578 self.__class__.placement1['description'] += ' Even more description.'579 self.__class__.placement2['description'] += ' Even more description.'580 placements = self.__class__.service.UpdatePlacements([581 self.__class__.placement1, self.__class__.placement2])582 self.assert_(isinstance(placements, tuple))583 self.__class__.placement1['targetedAdUnitIds'].append(584 self.__class__.ad_unit_id4)585 self.__class__.placement2['targetedAdUnitIds'].append(586 self.__class__.ad_unit_id4)587 placements = self.__class__.service.UpdatePlacements([588 self.__class__.placement1, self.__class__.placement2])589 self.assert_(isinstance(placements, tuple))590def makeTestSuiteV201004():591 """Set up test suite using v201004.592 Returns:593 TestSuite test suite using v201004.594 """595 suite = unittest.TestSuite()596 suite.addTests(unittest.makeSuite(PlacementServiceTestV201004))597 return suite598def makeTestSuiteV201010():599 """Set up test suite using v201010.600 Returns:601 TestSuite test suite using v201010.602 """603 suite = unittest.TestSuite()604 suite.addTests(unittest.makeSuite(PlacementServiceTestV201010))605 return suite606def makeTestSuiteV201101():607 """Set up test suite using v201101.608 Returns:609 TestSuite test suite using v201101.610 """611 suite = unittest.TestSuite()612 suite.addTests(unittest.makeSuite(PlacementServiceTestV201101))613 return suite614def makeTestSuiteV201103():615 """Set up test suite using v201103.616 Returns:617 TestSuite test suite using v201103.618 """619 suite = unittest.TestSuite()620 suite.addTests(unittest.makeSuite(PlacementServiceTestV201103))621 return suite622if __name__ == '__main__':623 suite_v201004 = makeTestSuiteV201004()624 suite_v201010 = makeTestSuiteV201010()625 suite_v201101 = makeTestSuiteV201101()626 suite_v201103 = makeTestSuiteV201103()627 alltests = unittest.TestSuite([suite_v201004, suite_v201010, suite_v201101,628 suite_v201103])...

Full Screen

Full Screen

order_service_unittest.py

Source:order_service_unittest.py Github

copy

Full Screen

1#!/usr/bin/python2# -*- coding: UTF-8 -*-3#4# Copyright 2011 Google Inc. All Rights Reserved.5#6# Licensed under the Apache License, Version 2.0 (the "License");7# you may not use this file except in compliance with the License.8# You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing, software13# distributed under the License is distributed on an "AS IS" BASIS,14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15# See the License for the specific language governing permissions and16# limitations under the License.17"""Unit tests to cover OrderService."""18__author__ = 'api.sgrinberg@gmail.com (Stan Grinberg)'19import os20import sys21sys.path.append(os.path.join('..', '..', '..'))22import unittest23from adspygoogle.common import Utils24from tests.adspygoogle.dfp import HTTP_PROXY25from tests.adspygoogle.dfp import SERVER_V20100426from tests.adspygoogle.dfp import SERVER_V20101027from tests.adspygoogle.dfp import SERVER_V20110128from tests.adspygoogle.dfp import SERVER_V20110329from tests.adspygoogle.dfp import VERSION_V20100430from tests.adspygoogle.dfp import VERSION_V20101031from tests.adspygoogle.dfp import VERSION_V20110132from tests.adspygoogle.dfp import VERSION_V20110333from tests.adspygoogle.dfp import client34class OrderServiceTestV201004(unittest.TestCase):35 """Unittest suite for OrderService using v201004."""36 SERVER = SERVER_V20100437 VERSION = VERSION_V20100438 client.debug = False39 service = None40 advertiser_id = '0'41 salesperson_id = '0'42 trafficker_id = '0'43 order1 = None44 order2 = None45 def setUp(self):46 """Prepare unittest."""47 print self.id()48 if not self.__class__.service:49 self.__class__.service = client.GetOrderService(50 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)51 if self.__class__.advertiser_id == '0':52 company = {53 'name': 'Company #%s' % Utils.GetUniqueName(),54 'type': 'ADVERTISER'55 }56 self.__class__.advertiser_id = client.GetCompanyService(57 self.__class__.SERVER, self.__class__.VERSION,58 HTTP_PROXY).CreateCompany(company)[0]['id']59 if self.__class__.trafficker_id == '0':60 filter_statement = {'query': 'ORDER BY name LIMIT 500'}61 users = client.GetUserService(62 self.__class__.SERVER, self.__class__.VERSION,63 HTTP_PROXY).GetUsersByStatement(filter_statement)64 for user in users[0]['results']:65 if user['roleName'] in ('Salesperson',):66 self.__class__.salesperson_id = user['id']67 continue68 elif user['roleName'] in ('Trafficker',):69 self.__class__.trafficker_id = user['id']70 continue71 def testCreateOrder(self):72 """Test whether we can create an order."""73 order = {74 'advertiserId': self.__class__.advertiser_id,75 'currencyCode': 'USD',76 'name': 'Order #%s' % Utils.GetUniqueName(),77 'traffickerId': self.__class__.trafficker_id78 }79 self.assert_(isinstance(80 self.__class__.service.CreateOrder(order), tuple))81 def testCreateOrders(self):82 """Test whether we can create a list of orders."""83 orders = [84 {85 'advertiserId': self.__class__.advertiser_id,86 'currencyCode': 'USD',87 'name': 'Order #%s' % Utils.GetUniqueName(),88 'traffickerId': self.__class__.trafficker_id89 },90 {91 'advertiserId': self.__class__.advertiser_id,92 'currencyCode': 'USD',93 'name': 'Order #%s' % Utils.GetUniqueName(),94 'traffickerId': self.__class__.trafficker_id95 }96 ]97 orders = self.__class__.service.CreateOrders(orders)98 self.__class__.order1 = orders[0]99 self.__class__.order2 = orders[1]100 self.assert_(isinstance(orders, tuple))101 def testGetOrder(self):102 """Test whether we can fetch an existing order."""103 if not self.__class__.order1:104 self.testCreateOrders()105 self.assert_(isinstance(self.__class__.service.GetOrder(106 self.__class__.order1['id']), tuple))107 def testGetOrdersByStatement(self):108 """Test whether we can fetch a list of existing orders that match given109 statement."""110 if not self.__class__.order1:111 self.testCreateOrders()112 filter_statement = {'query': 'WHERE advertiserId = \'%s\' LIMIT 500'113 % self.__class__.advertiser_id}114 self.assert_(isinstance(115 self.__class__.service.GetOrdersByStatement(filter_statement),116 tuple))117 def testPerformOrderAction(self):118 """Test whether we can approve order."""119 action = {'type': 'ApproveOrders'}120 filter_statement = {'query': 'WHERE status = \'DRAFT\''}121 self.assert_(isinstance(122 self.__class__.service.PerformOrderAction(action, filter_statement),123 tuple))124 def testUpdateOrder(self):125 """Test whether we can update an order."""126 if not self.__class__.order1:127 self.testCreateOrders()128 notes = 'Spoke to advertiser. All is well.'129 self.__class__.order1['notes'] = notes130 order = self.__class__.service.UpdateOrder(self.__class__.order1)131 self.assert_(isinstance(order, tuple))132 self.assertEqual(order[0]['notes'], notes)133 def testUpdateOrders(self):134 """Test whether we can update a list of orders."""135 if not self.__class__.order1 or not self.__class__.order2:136 self.testCreateOrders()137 notes = 'Spoke to advertiser. All is well.'138 self.__class__.order1['notes'] = notes139 self.__class__.order2['notes'] = notes140 orders = self.__class__.service.UpdateOrders([self.__class__.order1,141 self.__class__.order2])142 self.assert_(isinstance(orders, tuple))143 for order in orders:144 self.assertEqual(order['notes'], notes)145class OrderServiceTestV201010(unittest.TestCase):146 """Unittest suite for OrderService using v201010."""147 SERVER = SERVER_V201010148 VERSION = VERSION_V201010149 client.debug = False150 service = None151 advertiser_id = '0'152 salesperson_id = '0'153 trafficker_id = '0'154 order1 = None155 order2 = None156 def setUp(self):157 """Prepare unittest."""158 print self.id()159 if not self.__class__.service:160 self.__class__.service = client.GetOrderService(161 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)162 if self.__class__.advertiser_id == '0':163 company = {164 'name': 'Company #%s' % Utils.GetUniqueName(),165 'type': 'ADVERTISER'166 }167 self.__class__.advertiser_id = client.GetCompanyService(168 self.__class__.SERVER, self.__class__.VERSION,169 HTTP_PROXY).CreateCompany(company)[0]['id']170 if self.__class__.trafficker_id == '0':171 filter_statement = {'query': 'ORDER BY name LIMIT 500'}172 users = client.GetUserService(173 self.__class__.SERVER, self.__class__.VERSION,174 HTTP_PROXY).GetUsersByStatement(filter_statement)175 for user in users[0]['results']:176 if user['roleName'] in ('Salesperson',):177 self.__class__.salesperson_id = user['id']178 continue179 elif user['roleName'] in ('Trafficker',):180 self.__class__.trafficker_id = user['id']181 continue182 def testCreateOrder(self):183 """Test whether we can create an order."""184 order = {185 'advertiserId': self.__class__.advertiser_id,186 'currencyCode': 'USD',187 'name': 'Order #%s' % Utils.GetUniqueName(),188 'traffickerId': self.__class__.trafficker_id189 }190 self.assert_(isinstance(191 self.__class__.service.CreateOrder(order), tuple))192 def testCreateOrders(self):193 """Test whether we can create a list of orders."""194 orders = [195 {196 'advertiserId': self.__class__.advertiser_id,197 'currencyCode': 'USD',198 'name': 'Order #%s' % Utils.GetUniqueName(),199 'traffickerId': self.__class__.trafficker_id200 },201 {202 'advertiserId': self.__class__.advertiser_id,203 'currencyCode': 'USD',204 'name': 'Order #%s' % Utils.GetUniqueName(),205 'traffickerId': self.__class__.trafficker_id206 }207 ]208 orders = self.__class__.service.CreateOrders(orders)209 self.__class__.order1 = orders[0]210 self.__class__.order2 = orders[1]211 self.assert_(isinstance(orders, tuple))212 def testGetOrder(self):213 """Test whether we can fetch an existing order."""214 if not self.__class__.order1:215 self.testCreateOrders()216 self.assert_(isinstance(self.__class__.service.GetOrder(217 self.__class__.order1['id']), tuple))218 def testGetOrdersByStatement(self):219 """Test whether we can fetch a list of existing orders that match given220 statement."""221 if not self.__class__.order1:222 self.testCreateOrders()223 filter_statement = {'query': 'WHERE advertiserId = \'%s\' LIMIT 500'224 % self.__class__.advertiser_id}225 self.assert_(isinstance(226 self.__class__.service.GetOrdersByStatement(filter_statement),227 tuple))228 def testPerformOrderAction(self):229 """Test whether we can approve order."""230 action = {'type': 'ApproveOrders'}231 filter_statement = {'query': 'WHERE status = \'DRAFT\''}232 self.assert_(isinstance(233 self.__class__.service.PerformOrderAction(action, filter_statement),234 tuple))235 def testUpdateOrder(self):236 """Test whether we can update an order."""237 if not self.__class__.order1:238 self.testCreateOrders()239 notes = 'Spoke to advertiser. All is well.'240 self.__class__.order1['notes'] = notes241 order = self.__class__.service.UpdateOrder(self.__class__.order1)242 self.assert_(isinstance(order, tuple))243 self.assertEqual(order[0]['notes'], notes)244 def testUpdateOrders(self):245 """Test whether we can update a list of orders."""246 if not self.__class__.order1 or not self.__class__.order2:247 self.testCreateOrders()248 notes = 'Spoke to advertiser. All is well.'249 self.__class__.order1['notes'] = notes250 self.__class__.order2['notes'] = notes251 orders = self.__class__.service.UpdateOrders([self.__class__.order1,252 self.__class__.order2])253 self.assert_(isinstance(orders, tuple))254 for order in orders:255 self.assertEqual(order['notes'], notes)256class OrderServiceTestV201101(unittest.TestCase):257 """Unittest suite for OrderService using v201101."""258 SERVER = SERVER_V201101259 VERSION = VERSION_V201101260 client.debug = False261 service = None262 advertiser_id = '0'263 salesperson_id = '0'264 trafficker_id = '0'265 order1 = None266 order2 = None267 def setUp(self):268 """Prepare unittest."""269 print self.id()270 if not self.__class__.service:271 self.__class__.service = client.GetOrderService(272 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)273 if self.__class__.advertiser_id == '0':274 company = {275 'name': 'Company #%s' % Utils.GetUniqueName(),276 'type': 'ADVERTISER'277 }278 self.__class__.advertiser_id = client.GetCompanyService(279 self.__class__.SERVER, self.__class__.VERSION,280 HTTP_PROXY).CreateCompany(company)[0]['id']281 if self.__class__.trafficker_id == '0':282 filter_statement = {'query': 'ORDER BY name LIMIT 500'}283 users = client.GetUserService(284 self.__class__.SERVER, self.__class__.VERSION,285 HTTP_PROXY).GetUsersByStatement(filter_statement)286 for user in users[0]['results']:287 if user['roleName'] in ('Salesperson',):288 self.__class__.salesperson_id = user['id']289 continue290 elif user['roleName'] in ('Trafficker',):291 self.__class__.trafficker_id = user['id']292 continue293 def testCreateOrder(self):294 """Test whether we can create an order."""295 order = {296 'advertiserId': self.__class__.advertiser_id,297 'currencyCode': 'USD',298 'name': 'Order #%s' % Utils.GetUniqueName(),299 'traffickerId': self.__class__.trafficker_id300 }301 self.assert_(isinstance(302 self.__class__.service.CreateOrder(order), tuple))303 def testCreateOrders(self):304 """Test whether we can create a list of orders."""305 orders = [306 {307 'advertiserId': self.__class__.advertiser_id,308 'currencyCode': 'USD',309 'name': 'Order #%s' % Utils.GetUniqueName(),310 'traffickerId': self.__class__.trafficker_id311 },312 {313 'advertiserId': self.__class__.advertiser_id,314 'currencyCode': 'USD',315 'name': 'Order #%s' % Utils.GetUniqueName(),316 'traffickerId': self.__class__.trafficker_id317 }318 ]319 orders = self.__class__.service.CreateOrders(orders)320 self.__class__.order1 = orders[0]321 self.__class__.order2 = orders[1]322 self.assert_(isinstance(orders, tuple))323 def testGetOrder(self):324 """Test whether we can fetch an existing order."""325 if not self.__class__.order1:326 self.testCreateOrders()327 self.assert_(isinstance(self.__class__.service.GetOrder(328 self.__class__.order1['id']), tuple))329 def testGetOrdersByStatement(self):330 """Test whether we can fetch a list of existing orders that match given331 statement."""332 if not self.__class__.order1:333 self.testCreateOrders()334 filter_statement = {'query': 'WHERE advertiserId = \'%s\' LIMIT 500'335 % self.__class__.advertiser_id}336 self.assert_(isinstance(337 self.__class__.service.GetOrdersByStatement(filter_statement),338 tuple))339 def testPerformOrderAction(self):340 """Test whether we can approve order."""341 action = {'type': 'ApproveOrders'}342 filter_statement = {'query': 'WHERE status = \'DRAFT\''}343 self.assert_(isinstance(344 self.__class__.service.PerformOrderAction(action, filter_statement),345 tuple))346 def testUpdateOrder(self):347 """Test whether we can update an order."""348 if not self.__class__.order1:349 self.testCreateOrders()350 notes = 'Spoke to advertiser. All is well.'351 self.__class__.order1['notes'] = notes352 order = self.__class__.service.UpdateOrder(self.__class__.order1)353 self.assert_(isinstance(order, tuple))354 self.assertEqual(order[0]['notes'], notes)355 def testUpdateOrders(self):356 """Test whether we can update a list of orders."""357 if not self.__class__.order1 or not self.__class__.order2:358 self.testCreateOrders()359 notes = 'Spoke to advertiser. All is well.'360 self.__class__.order1['notes'] = notes361 self.__class__.order2['notes'] = notes362 orders = self.__class__.service.UpdateOrders([self.__class__.order1,363 self.__class__.order2])364 self.assert_(isinstance(orders, tuple))365 for order in orders:366 self.assertEqual(order['notes'], notes)367class OrderServiceTestV201103(unittest.TestCase):368 """Unittest suite for OrderService using v201103."""369 SERVER = SERVER_V201103370 VERSION = VERSION_V201103371 client.debug = False372 service = None373 advertiser_id = '0'374 salesperson_id = '0'375 trafficker_id = '0'376 order1 = None377 order2 = None378 def setUp(self):379 """Prepare unittest."""380 print self.id()381 if not self.__class__.service:382 self.__class__.service = client.GetOrderService(383 self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)384 if self.__class__.advertiser_id == '0':385 company = {386 'name': 'Company #%s' % Utils.GetUniqueName(),387 'type': 'ADVERTISER'388 }389 self.__class__.advertiser_id = client.GetCompanyService(390 self.__class__.SERVER, self.__class__.VERSION,391 HTTP_PROXY).CreateCompany(company)[0]['id']392 if self.__class__.trafficker_id == '0':393 filter_statement = {'query': 'ORDER BY name LIMIT 500'}394 users = client.GetUserService(395 self.__class__.SERVER, self.__class__.VERSION,396 HTTP_PROXY).GetUsersByStatement(filter_statement)397 for user in users[0]['results']:398 if user['roleName'] in ('Salesperson',):399 self.__class__.salesperson_id = user['id']400 continue401 elif user['roleName'] in ('Trafficker',):402 self.__class__.trafficker_id = user['id']403 continue404 def testCreateOrder(self):405 """Test whether we can create an order."""406 order = {407 'advertiserId': self.__class__.advertiser_id,408 'currencyCode': 'USD',409 'name': 'Order #%s' % Utils.GetUniqueName(),410 'traffickerId': self.__class__.trafficker_id411 }412 self.assert_(isinstance(413 self.__class__.service.CreateOrder(order), tuple))414 def testCreateOrders(self):415 """Test whether we can create a list of orders."""416 orders = [417 {418 'advertiserId': self.__class__.advertiser_id,419 'currencyCode': 'USD',420 'name': 'Order #%s' % Utils.GetUniqueName(),421 'traffickerId': self.__class__.trafficker_id422 },423 {424 'advertiserId': self.__class__.advertiser_id,425 'currencyCode': 'USD',426 'name': 'Order #%s' % Utils.GetUniqueName(),427 'traffickerId': self.__class__.trafficker_id428 }429 ]430 orders = self.__class__.service.CreateOrders(orders)431 self.__class__.order1 = orders[0]432 self.__class__.order2 = orders[1]433 self.assert_(isinstance(orders, tuple))434 def testGetOrder(self):435 """Test whether we can fetch an existing order."""436 if not self.__class__.order1:437 self.testCreateOrders()438 self.assert_(isinstance(self.__class__.service.GetOrder(439 self.__class__.order1['id']), tuple))440 def testGetOrdersByStatement(self):441 """Test whether we can fetch a list of existing orders that match given442 statement."""443 if not self.__class__.order1:444 self.testCreateOrders()445 filter_statement = {'query': 'WHERE advertiserId = \'%s\' LIMIT 500'446 % self.__class__.advertiser_id}447 self.assert_(isinstance(448 self.__class__.service.GetOrdersByStatement(filter_statement),449 tuple))450 def testPerformOrderAction(self):451 """Test whether we can approve order."""452 action = {'type': 'ApproveOrders'}453 filter_statement = {'query': 'WHERE status = \'DRAFT\''}454 self.assert_(isinstance(455 self.__class__.service.PerformOrderAction(action, filter_statement),456 tuple))457 def testUpdateOrder(self):458 """Test whether we can update an order."""459 if not self.__class__.order1:460 self.testCreateOrders()461 notes = 'Spoke to advertiser. All is well.'462 self.__class__.order1['notes'] = notes463 order = self.__class__.service.UpdateOrder(self.__class__.order1)464 self.assert_(isinstance(order, tuple))465 self.assertEqual(order[0]['notes'], notes)466 def testUpdateOrders(self):467 """Test whether we can update a list of orders."""468 if not self.__class__.order1 or not self.__class__.order2:469 self.testCreateOrders()470 notes = 'Spoke to advertiser. All is well.'471 self.__class__.order1['notes'] = notes472 self.__class__.order2['notes'] = notes473 orders = self.__class__.service.UpdateOrders([self.__class__.order1,474 self.__class__.order2])475 self.assert_(isinstance(orders, tuple))476 for order in orders:477 self.assertEqual(order['notes'], notes)478def makeTestSuiteV201004():479 """Set up test suite using v201004.480 Returns:481 TestSuite test suite using v201004.482 """483 suite = unittest.TestSuite()484 suite.addTests(unittest.makeSuite(OrderServiceTestV201004))485 return suite486def makeTestSuiteV201010():487 """Set up test suite using v201010.488 Returns:489 TestSuite test suite using v201010.490 """491 suite = unittest.TestSuite()492 suite.addTests(unittest.makeSuite(OrderServiceTestV201010))493 return suite494def makeTestSuiteV201101():495 """Set up test suite using v201101.496 Returns:497 TestSuite test suite using v201101.498 """499 suite = unittest.TestSuite()500 suite.addTests(unittest.makeSuite(OrderServiceTestV201101))501 return suite502def makeTestSuiteV201103():503 """Set up test suite using v201103.504 Returns:505 TestSuite test suite using v201103.506 """507 suite = unittest.TestSuite()508 suite.addTests(unittest.makeSuite(OrderServiceTestV201103))509 return suite510if __name__ == '__main__':511 suite_v201004 = makeTestSuiteV201004()512 suite_v201010 = makeTestSuiteV201010()513 suite_v201101 = makeTestSuiteV201101()514 suite_v201103 = makeTestSuiteV201103()515 alltests = unittest.TestSuite([suite_v201004, suite_v201010, suite_v201101,516 suite_v201103])...

Full Screen

Full Screen

test_super.py

Source:test_super.py Github

copy

Full Screen

1"""Unit tests for new super() implementation."""2import sys3import unittest4class A:5 def f(self):6 return 'A'7 @classmethod8 def cm(cls):9 return (cls, 'A')10class B(A):11 def f(self):12 return super().f() + 'B'13 @classmethod14 def cm(cls):15 return (cls, super().cm(), 'B')16class C(A):17 def f(self):18 return super().f() + 'C'19 @classmethod20 def cm(cls):21 return (cls, super().cm(), 'C')22class D(C, B):23 def f(self):24 return super().f() + 'D'25 def cm(cls):26 return (cls, super().cm(), 'D')27class E(D):28 pass29class F(E):30 f = E.f31class G(A):32 pass33class TestSuper(unittest.TestCase):34 def tearDown(self):35 # This fixes the damage that test_various___class___pathologies does.36 nonlocal __class__37 __class__ = TestSuper38 def test_basics_working(self):39 self.assertEqual(D().f(), 'ABCD')40 def test_class_getattr_working(self):41 self.assertEqual(D.f(D()), 'ABCD')42 def test_subclass_no_override_working(self):43 self.assertEqual(E().f(), 'ABCD')44 self.assertEqual(E.f(E()), 'ABCD')45 def test_unbound_method_transfer_working(self):46 self.assertEqual(F().f(), 'ABCD')47 self.assertEqual(F.f(F()), 'ABCD')48 def test_class_methods_still_working(self):49 self.assertEqual(A.cm(), (A, 'A'))50 self.assertEqual(A().cm(), (A, 'A'))51 self.assertEqual(G.cm(), (G, 'A'))52 self.assertEqual(G().cm(), (G, 'A'))53 def test_super_in_class_methods_working(self):54 d = D()55 self.assertEqual(d.cm(), (d, (D, (D, (D, 'A'), 'B'), 'C'), 'D'))56 e = E()57 self.assertEqual(e.cm(), (e, (E, (E, (E, 'A'), 'B'), 'C'), 'D'))58 def test_super_with_closure(self):59 # Issue4360: super() did not work in a function that60 # contains a closure61 class E(A):62 def f(self):63 def nested():64 self65 return super().f() + 'E'66 self.assertEqual(E().f(), 'AE')67 def test_various___class___pathologies(self):68 # See issue #1237069 class X(A):70 def f(self):71 return super().f()72 __class__ = 41373 x = X()74 self.assertEqual(x.f(), 'A')75 self.assertEqual(x.__class__, 413)76 class X:77 x = __class__78 def f():79 __class__80 self.assertIs(X.x, type(self))81 with self.assertRaises(NameError) as e:82 exec("""class X:83 __class__84 def f():85 __class__""", globals(), {})86 self.assertIs(type(e.exception), NameError) # Not UnboundLocalError87 class X:88 global __class__89 __class__ = 4290 def f():91 __class__92 self.assertEqual(globals()["__class__"], 42)93 del globals()["__class__"]94 self.assertNotIn("__class__", X.__dict__)95 class X:96 nonlocal __class__97 __class__ = 4298 def f():99 __class__100 self.assertEqual(__class__, 42)101 def test___class___instancemethod(self):102 # See issue #14857103 class X:104 def f(self):105 return __class__106 self.assertIs(X().f(), X)107 def test___class___classmethod(self):108 # See issue #14857109 class X:110 @classmethod111 def f(cls):112 return __class__113 self.assertIs(X.f(), X)114 def test___class___staticmethod(self):115 # See issue #14857116 class X:117 @staticmethod118 def f():119 return __class__120 self.assertIs(X.f(), X)121 def test_obscure_super_errors(self):122 def f():123 super()124 self.assertRaises(RuntimeError, f)125 def f(x):126 del x127 super()128 self.assertRaises(RuntimeError, f, None)129 class X:130 def f(x):131 nonlocal __class__132 del __class__133 super()134 self.assertRaises(RuntimeError, X().f)135 def test_cell_as_self(self):136 class X:137 def meth(self):138 super()139 def f():140 k = X()141 def g():142 return k143 return g144 c = f().__closure__[0]145 self.assertRaises(TypeError, X.meth, c)146if __name__ == "__main__":...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful