Best Python code snippet using Airtest
gamelevel.py
Source:gamelevel.py
1'''2Function:3 ç¨äºè¿è¡æä¸æ¸¸æå
³å¡4Author:5 Charles6微信å
¬ä¼å·:7 Charlesçç®å¡ä¸8'''9import pygame10import random11from .sprites import *12from ....utils import QuitGame13'''ç¨äºè¿è¡æä¸æ¸¸æå
³å¡'''14class GameLevel():15 def __init__(self, gamelevel, levelfilepath, is_dual_mode, cfg, resource_loader, **kwargs):16 self.cfg = cfg17 # å
³å¡å°å¾è·¯å¾18 self.gamelevel = gamelevel19 self.levelfilepath = levelfilepath20 # èµæºå è½½å¨21 self.resource_loader = resource_loader22 self.sounds = self.resource_loader.sounds23 # æ¯å¦ä¸ºå人模å¼24 self.is_dual_mode = is_dual_mode25 # å°å¾è§æ¨¡åæ°26 self.border_len = cfg.BORDER_LEN27 self.grid_size = cfg.GRID_SIZE28 self.width, self.height = cfg.SCREENSIZE29 self.panel_width = cfg.PANEL_WIDTH30 # åä½31 self.font = resource_loader.fonts['gaming']32 # å
³å¡åºæ¯å
ç´ 33 self.scene_elems = {34 'brick_group': pygame.sprite.Group(), 35 'iron_group': pygame.sprite.Group(),36 'ice_group': pygame.sprite.Group(), 37 'river_group': pygame.sprite.Group(),38 'tree_group': pygame.sprite.Group()39 }40 # 解æå
³å¡æ件41 self.__parseLevelFile()42 '''å¼å§æ¸¸æ'''43 def start(self, screen):44 screen, resource_loader = pygame.display.set_mode((self.width+self.panel_width, self.height)), self.resource_loader45 # èæ¯å¾ç46 background_img = resource_loader.images['others']['background']47 # å®ä¹ç²¾çµç»48 player_tanks_group = pygame.sprite.Group()49 enemy_tanks_group = pygame.sprite.Group()50 player_bullets_group = pygame.sprite.Group()51 enemy_bullets_group = pygame.sprite.Group()52 foods_group = pygame.sprite.Group()53 # å®ä¹ææ¹å¦å
çæäºä»¶54 generate_enemies_event = pygame.constants.USEREVENT55 pygame.time.set_timer(generate_enemies_event, 20000)56 # ææ¹å¤§æ¬è¥57 home = Home(position=self.home_position, images=resource_loader.images['home'])58 # ææ¹å¦å
59 tank_player1 = PlayerTank(60 name='player1', position=self.player_tank_positions[0], player_tank_images=resource_loader.images['player'], 61 border_len=self.border_len, screensize=[self.width, self.height], bullet_images=resource_loader.images['bullet'], 62 protected_mask=resource_loader.images['others']['protect'], boom_image=resource_loader.images['others']['boom_static']63 )64 player_tanks_group.add(tank_player1)65 if self.is_dual_mode:66 tank_player2 = PlayerTank(67 name='player2', position=self.player_tank_positions[1], player_tank_images=resource_loader.images['player'], 68 border_len=self.border_len, screensize=[self.width, self.height], bullet_images=resource_loader.images['bullet'], 69 protected_mask=resource_loader.images['others']['protect'], boom_image=resource_loader.images['others']['boom_static']70 )71 player_tanks_group.add(tank_player2)72 # ææ¹å¦å
73 for position in self.enemy_tank_positions:74 enemy_tanks_group.add(EnemyTank(75 enemy_tank_images=resource_loader.images['enemy'], appear_image=resource_loader.images['others']['appear'], position=position, 76 border_len=self.border_len, screensize=[self.width, self.height], bullet_images=resource_loader.images['bullet'], 77 food_images=resource_loader.images['food'], boom_image=resource_loader.images['others']['boom_static']78 ))79 # 游æå¼å§é³ä¹80 self.sounds['start'].play()81 clock = pygame.time.Clock()82 # 该å
³å¡éè¿ä¸å¦çflags83 is_win = False84 is_running = True85 # 游æ主循ç¯86 while is_running:87 screen.fill((0, 0, 0))88 screen.blit(background_img, (0, 0))89 # ç¨æ·äºä»¶ææ90 for event in pygame.event.get():91 if event.type == pygame.QUIT:92 QuitGame()93 # --ææ¹å¦å
çæ94 elif event.type == generate_enemies_event:95 if self.max_enemy_num > len(enemy_tanks_group):96 for position in self.enemy_tank_positions:97 if len(enemy_tanks_group) == self.total_enemy_num:98 break99 enemy_tank = EnemyTank(100 enemy_tank_images=resource_loader.images['enemy'], appear_image=resource_loader.images['others']['appear'], position=position, 101 border_len=self.border_len, screensize=[self.width, self.height], bullet_images=resource_loader.images['bullet'], 102 food_images=resource_loader.images['food'], boom_image=resource_loader.images['others']['boom_static']103 )104 if (not pygame.sprite.spritecollide(enemy_tank, enemy_tanks_group, False, None)) and (not pygame.sprite.spritecollide(enemy_tank, player_tanks_group, False, None)):105 enemy_tanks_group.add(enemy_tank)106 # --ç¨æ·æé®107 key_pressed = pygame.key.get_pressed()108 # ç©å®¶ä¸, WSAD移å¨, ç©ºæ ¼é®å°å»109 if tank_player1.num_lifes >= 0:110 if key_pressed[pygame.K_w]:111 player_tanks_group.remove(tank_player1)112 tank_player1.move('up', self.scene_elems, player_tanks_group, enemy_tanks_group, home)113 player_tanks_group.add(tank_player1)114 elif key_pressed[pygame.K_s]:115 player_tanks_group.remove(tank_player1)116 tank_player1.move('down', self.scene_elems, player_tanks_group, enemy_tanks_group, home)117 player_tanks_group.add(tank_player1)118 elif key_pressed[pygame.K_a]:119 player_tanks_group.remove(tank_player1)120 tank_player1.move('left', self.scene_elems, player_tanks_group, enemy_tanks_group, home)121 player_tanks_group.add(tank_player1)122 elif key_pressed[pygame.K_d]:123 player_tanks_group.remove(tank_player1)124 tank_player1.move('right', self.scene_elems, player_tanks_group, enemy_tanks_group, home)125 player_tanks_group.add(tank_player1)126 elif key_pressed[pygame.K_SPACE]:127 bullet = tank_player1.shoot()128 if bullet:129 self.sounds['fire'].play() if tank_player1.tanklevel < 2 else self.sounds['Gunfire'].play()130 player_bullets_group.add(bullet)131 # ç©å®¶äº, ââââ移å¨, å°é®ç0é®å°å»132 if self.is_dual_mode and (tank_player2.num_lifes >= 0):133 if key_pressed[pygame.K_UP]:134 player_tanks_group.remove(tank_player2)135 tank_player2.move('up', self.scene_elems, player_tanks_group, enemy_tanks_group, home)136 player_tanks_group.add(tank_player2)137 elif key_pressed[pygame.K_DOWN]:138 player_tanks_group.remove(tank_player2)139 tank_player2.move('down', self.scene_elems, player_tanks_group, enemy_tanks_group, home)140 player_tanks_group.add(tank_player2)141 elif key_pressed[pygame.K_LEFT]:142 player_tanks_group.remove(tank_player2)143 tank_player2.move('left', self.scene_elems, player_tanks_group, enemy_tanks_group, home)144 player_tanks_group.add(tank_player2)145 elif key_pressed[pygame.K_RIGHT]:146 player_tanks_group.remove(tank_player2)147 tank_player2.move('right', self.scene_elems, player_tanks_group, enemy_tanks_group, home)148 player_tanks_group.add(tank_player2)149 elif key_pressed[pygame.K_KP0]:150 bullet = tank_player2.shoot()151 if bullet:152 player_bullets_group.add(bullet)153 self.sounds['fire'].play() if tank_player2.tanklevel < 2 else self.sounds['Gunfire'].play()154 # 碰ææ£æµ155 # --åå¼¹åç å¢156 pygame.sprite.groupcollide(player_bullets_group, self.scene_elems.get('brick_group'), True, True)157 pygame.sprite.groupcollide(enemy_bullets_group, self.scene_elems.get('brick_group'), True, True)158 # --åå¼¹åéå¢159 for bullet in player_bullets_group:160 if pygame.sprite.spritecollide(bullet, self.scene_elems.get('iron_group'), bullet.is_stronger, None):161 player_bullets_group.remove(bullet)162 pygame.sprite.groupcollide(enemy_bullets_group, self.scene_elems.get('iron_group'), True, False)163 # --åå¼¹æåå¼¹164 pygame.sprite.groupcollide(player_bullets_group, enemy_bullets_group, True, True)165 # --ææ¹åå¼¹æææ¹å¦å
166 for tank in enemy_tanks_group:167 if pygame.sprite.spritecollide(tank, player_bullets_group, True, None):168 if tank.food:169 foods_group.add(tank.food)170 tank.food = None171 if tank.decreaseTankLevel():172 self.sounds['bang'].play()173 self.total_enemy_num -= 1174 # --ææ¹åå¼¹æææ¹å¦å
175 for tank in player_tanks_group:176 if pygame.sprite.spritecollide(tank, enemy_bullets_group, True, None):177 if tank.is_protected:178 self.sounds['blast'].play()179 else:180 if tank.decreaseTankLevel():181 self.sounds['bang'].play()182 if tank.num_lifes < 0:183 player_tanks_group.remove(tank)184 # --ææ¹åå¼¹æææ¹å¤§æ¬è¥185 if pygame.sprite.spritecollide(home, player_bullets_group, True, None):186 is_win = False187 is_running = False188 home.setDead()189 # --ææ¹åå¼¹æææ¹å¤§æ¬è¥190 if pygame.sprite.spritecollide(home, enemy_bullets_group, True, None):191 is_win = False192 is_running = False193 home.setDead()194 # --ææ¹å¦å
å¨æ¤ç©é195 if pygame.sprite.groupcollide(player_tanks_group, self.scene_elems.get('tree_group'), False, False):196 self.sounds['hit'].play()197 # --ææ¹å¦å
åå°é£ç©198 for player_tank in player_tanks_group:199 for food in foods_group:200 if pygame.sprite.collide_rect(player_tank, food):201 if food.name == 'boom':202 self.sounds['add'].play()203 for _ in enemy_tanks_group:204 self.sounds['bang'].play()205 self.total_enemy_num -= len(enemy_tanks_group)206 enemy_tanks_group = pygame.sprite.Group()207 elif food.name == 'clock':208 self.sounds['add'].play()209 for enemy_tank in enemy_tanks_group:210 enemy_tank.setStill()211 elif food.name == 'gun':212 self.sounds['add'].play()213 player_tank.improveTankLevel()214 elif food.name == 'iron':215 self.sounds['add'].play()216 self.__pretectHome()217 elif food.name == 'protect':218 self.sounds['add'].play()219 player_tank.setProtected()220 elif food.name == 'star':221 self.sounds['add'].play()222 player_tank.improveTankLevel()223 player_tank.improveTankLevel()224 elif food.name == 'tank':225 self.sounds['add'].play()226 player_tank.addLife()227 foods_group.remove(food)228 # ç»åºæ¯å°å¾229 for key, value in self.scene_elems.items():230 if key in ['ice_group', 'river_group']:231 value.draw(screen)232 # æ´æ°å¹¶ç»ææ¹åå¼¹233 for bullet in player_bullets_group:234 if bullet.move():235 player_bullets_group.remove(bullet)236 player_bullets_group.draw(screen)237 # æ´æ°å¹¶ç»ææ¹åå¼¹238 for bullet in enemy_bullets_group:239 if bullet.move():240 enemy_bullets_group.remove(bullet)241 enemy_bullets_group.draw(screen)242 # æ´æ°å¹¶ç»ææ¹å¦å
243 for tank in player_tanks_group:244 tank.update()245 tank.draw(screen)246 # æ´æ°å¹¶ç»ææ¹å¦å
247 for tank in enemy_tanks_group:248 enemy_tanks_group.remove(tank)249 data_return = tank.update(self.scene_elems, player_tanks_group, enemy_tanks_group, home)250 enemy_tanks_group.add(tank)251 if data_return.get('bullet'):252 enemy_bullets_group.add(data_return.get('bullet'))253 if data_return.get('boomed'):254 enemy_tanks_group.remove(tank)255 enemy_tanks_group.draw(screen)256 # ç»åºæ¯å°å¾257 for key, value in self.scene_elems.items():258 if key not in ['ice_group', 'river_group']:259 value.draw(screen)260 # ç»å¤§æ¬è¥261 home.draw(screen)262 # æ´æ°å¹¶æ¾ç¤ºé£ç©263 for food in foods_group:264 if food.update():265 foods_group.remove(food)266 foods_group.draw(screen)267 self.__showGamePanel(screen, tank_player1, tank_player2) if self.is_dual_mode else self.__showGamePanel(screen, tank_player1)268 # ææ¹å¦å
é½æäº269 if len(player_tanks_group) == 0:270 is_win = False271 is_running = False272 # ææ¹å¦å
é½æäº273 if self.total_enemy_num <= 0:274 is_win = True275 is_running = False276 pygame.display.flip()277 clock.tick(self.cfg.FPS)278 screen = pygame.display.set_mode((self.width, self.height))279 return is_win280 '''æ¾ç¤ºæ¸¸æé¢æ¿'''281 def __showGamePanel(self, screen, tank_player1, tank_player2=None):282 color_white = (255, 255, 255)283 # ç©å®¶ä¸æä½æ示284 player1_operate_tip = self.font.render('Operate-P1:', True, color_white)285 player1_operate_tip_rect = player1_operate_tip.get_rect()286 player1_operate_tip_rect.left, player1_operate_tip_rect.top = self.width+5, self.height/30287 screen.blit(player1_operate_tip, player1_operate_tip_rect)288 player1_operate_tip = self.font.render('K_w: Up', True, color_white)289 player1_operate_tip_rect = player1_operate_tip.get_rect()290 player1_operate_tip_rect.left, player1_operate_tip_rect.top = self.width+5, self.height*2/30291 screen.blit(player1_operate_tip, player1_operate_tip_rect)292 player1_operate_tip = self.font.render('K_s: Down', True, color_white)293 player1_operate_tip_rect = player1_operate_tip.get_rect()294 player1_operate_tip_rect.left, player1_operate_tip_rect.top = self.width+5, self.height*3/30295 screen.blit(player1_operate_tip, player1_operate_tip_rect)296 player1_operate_tip = self.font.render('K_a: Left', True, color_white)297 player1_operate_tip_rect = player1_operate_tip.get_rect()298 player1_operate_tip_rect.left, player1_operate_tip_rect.top = self.width+5, self.height*4/30299 screen.blit(player1_operate_tip, player1_operate_tip_rect)300 player1_operate_tip = self.font.render('K_d: Right', True, color_white)301 player1_operate_tip_rect = player1_operate_tip.get_rect()302 player1_operate_tip_rect.left, player1_operate_tip_rect.top = self.width+5, self.height*5/30303 screen.blit(player1_operate_tip, player1_operate_tip_rect)304 player1_operate_tip = self.font.render('K_SPACE: Shoot', True, color_white)305 player1_operate_tip_rect = player1_operate_tip.get_rect()306 player1_operate_tip_rect.left, player1_operate_tip_rect.top = self.width+5, self.height*6/30307 screen.blit(player1_operate_tip, player1_operate_tip_rect)308 # ç©å®¶äºæä½æ示309 player2_operate_tip = self.font.render('Operate-P2:', True, color_white)310 player2_operate_tip_rect = player2_operate_tip.get_rect()311 player2_operate_tip_rect.left, player2_operate_tip_rect.top = self.width+5, self.height*8/30312 screen.blit(player2_operate_tip, player2_operate_tip_rect)313 player2_operate_tip = self.font.render('K_UP: Up', True, color_white)314 player2_operate_tip_rect = player2_operate_tip.get_rect()315 player2_operate_tip_rect.left, player2_operate_tip_rect.top = self.width+5, self.height*9/30316 screen.blit(player2_operate_tip, player2_operate_tip_rect)317 player2_operate_tip = self.font.render('K_DOWN: Down', True, color_white)318 player2_operate_tip_rect = player2_operate_tip.get_rect()319 player2_operate_tip_rect.left, player2_operate_tip_rect.top = self.width+5, self.height*10/30320 screen.blit(player2_operate_tip, player2_operate_tip_rect)321 player2_operate_tip = self.font.render('K_LEFT: Left', True, color_white)322 player2_operate_tip_rect = player2_operate_tip.get_rect()323 player2_operate_tip_rect.left, player2_operate_tip_rect.top = self.width+5, self.height*11/30324 screen.blit(player2_operate_tip, player2_operate_tip_rect)325 player2_operate_tip = self.font.render('K_RIGHT: Right', True, color_white)326 player2_operate_tip_rect = player2_operate_tip.get_rect()327 player2_operate_tip_rect.left, player2_operate_tip_rect.top = self.width+5, self.height*12/30328 screen.blit(player2_operate_tip, player2_operate_tip_rect)329 player2_operate_tip = self.font.render('K_KP0: Shoot', True, color_white)330 player2_operate_tip_rect = player2_operate_tip.get_rect()331 player2_operate_tip_rect.left, player2_operate_tip_rect.top = self.width+5, self.height*13/30332 screen.blit(player2_operate_tip, player2_operate_tip_rect)333 # ç©å®¶ä¸ç¶ææ示334 player1_state_tip = self.font.render('State-P1:', True, color_white)335 player1_state_tip_rect = player1_state_tip.get_rect()336 player1_state_tip_rect.left, player1_state_tip_rect.top = self.width+5, self.height*15/30337 screen.blit(player1_state_tip, player1_state_tip_rect)338 player1_state_tip = self.font.render('Life: %s' % tank_player1.num_lifes, True, color_white)339 player1_state_tip_rect = player1_state_tip.get_rect()340 player1_state_tip_rect.left, player1_state_tip_rect.top = self.width+5, self.height*16/30341 screen.blit(player1_state_tip, player1_state_tip_rect)342 player1_state_tip = self.font.render('TLevel: %s' % tank_player1.tanklevel, True, color_white)343 player1_state_tip_rect = player1_state_tip.get_rect()344 player1_state_tip_rect.left, player1_state_tip_rect.top = self.width+5, self.height*17/30345 screen.blit(player1_state_tip, player1_state_tip_rect)346 # ç©å®¶äºç¶ææ示347 player2_state_tip = self.font.render('State-P2:', True, color_white)348 player2_state_tip_rect = player2_state_tip.get_rect()349 player2_state_tip_rect.left, player2_state_tip_rect.top = self.width+5, self.height*19/30350 screen.blit(player2_state_tip, player2_state_tip_rect)351 player2_state_tip = self.font.render('Life: %s' % tank_player2.num_lifes, True, color_white) if tank_player2 else self.font.render('Life: None', True, color_white)352 player2_state_tip_rect = player2_state_tip.get_rect()353 player2_state_tip_rect.left, player2_state_tip_rect.top = self.width+5, self.height*20/30354 screen.blit(player2_state_tip, player2_state_tip_rect)355 player2_state_tip = self.font.render('TLevel: %s' % tank_player2.tanklevel, True, color_white) if tank_player2 else self.font.render('TLevel: None', True, color_white)356 player2_state_tip_rect = player2_state_tip.get_rect()357 player2_state_tip_rect.left, player2_state_tip_rect.top = self.width+5, self.height*21/30358 screen.blit(player2_state_tip, player2_state_tip_rect)359 # å½åå
³å¡360 game_level_tip = self.font.render('Game Level: %s' % self.gamelevel, True, color_white)361 game_level_tip_rect = game_level_tip.get_rect()362 game_level_tip_rect.left, game_level_tip_rect.top = self.width+5, self.height*23/30363 screen.blit(game_level_tip, game_level_tip_rect)364 # å©ä½æ人æ°é365 remaining_enemy_tip = self.font.render('Remain Enemy: %s' % self.total_enemy_num, True, color_white)366 remaining_enemy_tip_rect = remaining_enemy_tip.get_rect()367 remaining_enemy_tip_rect.left, remaining_enemy_tip_rect.top = self.width+5, self.height*24/30368 screen.blit(remaining_enemy_tip, remaining_enemy_tip_rect)369 '''ä¿æ¤å¤§æ¬è¥'''370 def __pretectHome(self):371 for x, y in self.home_around_positions:372 self.scene_elems['iron_group'].add(Iron((x, y), self.resource_loader.images['scene']['iron']))373 '''解æå
³å¡æ件'''374 def __parseLevelFile(self):375 f = open(self.levelfilepath, errors='ignore')376 num_row = -1377 for line in f.readlines():378 line = line.strip('\n')379 # 注é380 if line.startswith('#') or (not line):381 continue382 # ææ¹å¦å
æ»æ°é383 elif line.startswith('%TOTALENEMYNUM'):384 self.total_enemy_num = int(line.split(':')[-1])385 # åºä¸ææ¹å¦å
æ大æ°é386 elif line.startswith('%MAXENEMYNUM'):387 self.max_enemy_num = int(line.split(':')[-1])388 # 大æ¬è¥ä½ç½®389 elif line.startswith('%HOMEPOS'):390 self.home_position = line.split(':')[-1]391 self.home_position = [int(self.home_position.split(',')[0]), int(self.home_position.split(',')[1])]392 self.home_position = (self.border_len+self.home_position[0]*self.grid_size, self.border_len+self.home_position[1]*self.grid_size)393 # 大æ¬è¥å¨å´ä½ç½®394 elif line.startswith('%HOMEAROUNDPOS'):395 self.home_around_positions = line.split(':')[-1]396 self.home_around_positions = [[int(pos.split(',')[0]), int(pos.split(',')[1])] for pos in self.home_around_positions.split(' ')]397 self.home_around_positions = [(self.border_len+pos[0]*self.grid_size, self.border_len+pos[1]*self.grid_size) for pos in self.home_around_positions]398 # ææ¹å¦å
åå§ä½ç½®399 elif line.startswith('%PLAYERTANKPOS'):400 self.player_tank_positions = line.split(':')[-1]401 self.player_tank_positions = [[int(pos.split(',')[0]), int(pos.split(',')[1])] for pos in self.player_tank_positions.split(' ')]402 self.player_tank_positions = [(self.border_len+pos[0]*self.grid_size, self.border_len+pos[1]*self.grid_size) for pos in self.player_tank_positions]403 # ææ¹å¦å
åå§ä½ç½®404 elif line.startswith('%ENEMYTANKPOS'):405 self.enemy_tank_positions = line.split(':')[-1]406 self.enemy_tank_positions = [[int(pos.split(',')[0]), int(pos.split(',')[1])] for pos in self.enemy_tank_positions.split(' ')]407 self.enemy_tank_positions = [(self.border_len+pos[0]*self.grid_size, self.border_len+pos[1]*self.grid_size) for pos in self.enemy_tank_positions]408 # å°å¾å
ç´ 409 else:410 num_row += 1411 for num_col, elem in enumerate(line.split(' ')):412 position = self.border_len+num_col*self.grid_size, self.border_len+num_row*self.grid_size413 if elem == 'B':414 self.scene_elems['brick_group'].add(Brick(position, self.resource_loader.images['scene']['brick']))415 elif elem == 'I':416 self.scene_elems['iron_group'].add(Iron(position, self.resource_loader.images['scene']['iron']))417 elif elem == 'R':418 self.scene_elems['river_group'].add(River(position, random.choice([self.resource_loader.images['scene']['river1'], self.resource_loader.images['scene']['river2']])))419 elif elem == 'C':420 self.scene_elems['ice_group'].add(Ice(position, self.resource_loader.images['scene']['ice']))421 elif elem == 'T':...
manager.py
Source:manager.py
1# -*- coding: utf-8 -*-2"""3Tencent is pleased to support the open source community by making è鲸æºäºPaaSå¹³å°ç¤¾åºç (BlueKing PaaS Community Edition) available.4Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.5Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at6http://opensource.org/licenses/MIT7Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.8""" # noqa9from __future__ import unicode_literals10import datetime11from django.db import models12from django.utils.html import escape13from common.log import logger14from release.constants import (APP_ALL_OPERATE_ID_LIST,15 APP_DID_OPERATE_ID_LIST,16 APP_OFFLINE_OPERATE_ID_LIST,17 APP_ONGOING_OPERATE_ID_LIST,18 APP_ONLINE_OPERATE_ID_LIST,19 APP_TEST_OPERATE_ID_LIST,20 OperateCodeEnum)21class ReleaseVersionManager(models.Manager):22 def create_version(self, appobj, bugs, features, username):23 """å建çæ¬24 """25 if not (bugs or features):26 return False27 is_exists = self.filter(app=appobj).exists()28 if is_exists:29 new_version = self.filter(app=appobj).order_by('-pubdate')[0].version30 new_version = int(''.join(new_version.split('.'))) + 131 version = '.'.join([n for n in str(new_version)])32 else:33 version = '1.0.0.1'34 try:35 self.create(app=appobj,36 version=version,37 publisher=username,38 pubdate=datetime.datetime.now()39 )40 self.get(app=appobj, version=version).versiondetail_set.create(bug=bugs, features=features)41 except Exception as e:42 logger.exception("å建åå¸æ°çæ¬å¤±è´¥!%s", e)43 return False44 return True45 def get_version_list(self, app):46 version_list = []47 versions = self.filter(app=app).order_by("-pubdate")48 for v in versions:49 version_details = v.versiondetail_set.all()50 bug_list = [escape(_detail.bug).replace('\n', '<br/>')51 for _detail in version_details if _detail.bug]52 features_list = [escape(_detail.features).replace('\n', '<br/>')53 for _detail in version_details if _detail.features]54 version_list.append({55 "version": v.version,56 "publisher": v.publisher,57 "pubdate": v.pubdate_display,58 "features": features_list,59 "bug": bug_list,60 })61 return version_list62class UserOperateRecordManager(models.Manager):63 def create_operate_record(self, app_code, username, operate_type, before_data='', arfter_data='', extra_data=''):64 """å建æä½è®°å½65 @param app_code: appç¼ç 66 @param username: æä½äºº67 @param operate_type: æä½ç±»å68 @param before_data: æä½åæ°æ®69 @param arfter_data: æä½åæ°æ®70 @param extra_data: å
¶ä»æ°æ®71 """72 try:73 self.create(74 app_code=app_code,75 username=username,76 before_data=before_data,77 arfter_data=arfter_data,78 operate_time=datetime.datetime.now(),79 operate_type=operate_type,80 extra_data=extra_data,81 )82 result = True83 except Exception as e:84 logger.exception("ç¨æ·æä½è®°å½å建失败ï¼errorï¼%s", e)85 result = False86 return result87class ReleaseRecordManager(models.Manager):88 def create_record(self, app_code, app_old_state, operate_user, operate_id, is_success):89 """90 å建记å½91 """92 record_obj = self.create(93 app_code=app_code,94 app_old_state=app_old_state,95 operate_user=operate_user,96 operate_id=operate_id,97 is_success=is_success,98 operate_time=datetime.datetime.now(),99 )100 return record_obj101 def get_latest_did_record(self, app_code):102 record = self.filter(operate_id__in=APP_DID_OPERATE_ID_LIST,103 app_code=app_code)\104 .order_by("-id")\105 .first()106 if not record:107 return None108 return {109 "username": record.operate_user,110 "datetime": record.operate_time_display,111 "operate_type": record.get_operate_id_display(),112 "result": "æå" if record.is_success else "失败",113 }114 def query_records(self, app_code, operate_code, size=100):115 query = self.filter(app_code=app_code)116 id_list = {117 OperateCodeEnum.ALL.value: APP_ALL_OPERATE_ID_LIST,118 OperateCodeEnum.TEST.value: APP_TEST_OPERATE_ID_LIST,119 OperateCodeEnum.ONLINE.value: APP_ONLINE_OPERATE_ID_LIST,120 OperateCodeEnum.OFFLINE.value: APP_OFFLINE_OPERATE_ID_LIST,121 }.get(operate_code)122 query = query.filter(operate_id__in=id_list).order_by("-operate_time")[0:size]123 return query124 def get_last_ongoing_records(self, app_code, size=10):125 records = self.filter(app_code=app_code)\126 .filter(operate_id__in=APP_ONGOING_OPERATE_ID_LIST)\127 .order_by("-id")[:size]128 return records129 def get_app_newest_record(self, app_code):130 # æ¥è¯¢æè¿ä¸æ¡, å¤äºè¿å ç§ç¶æçè®°å½, åæ¯appçææ°è®°å½131 record = self.filter(app_code=app_code)\132 .filter(operate_id__in=APP_ALL_OPERATE_ID_LIST)\133 .latest('id')...
constants.py
Source:constants.py
1# -*- coding: utf-8 -*-2"""3Tencent is pleased to support the open source community by making è鲸æºäºPaaSå¹³å°ç¤¾åºç (BlueKing PaaS Community Edition) available.4Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.5Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at6http://opensource.org/licenses/MIT7Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.8""" # noqa9from __future__ import unicode_literals10from enum import Enum11# ææµåä¸çº¿åç±»12class OperateIDEnum(Enum):13 TO_TEST = 014 TO_ONLINE = 115 TO_OFFLINE = 216 IN_TEST = 317 IN_ONLINE = 418 IN_OFFLINE = 519 REGISTER_INFO = 620 CREATE_DB = 721 INITIAL_CVS = 822 GRANT_DB_AUTH = 923 INITIAL_APP_CODE = 1024 DELETE_APP = 1125OPERATE_ID_CHOICES = [26 (OperateIDEnum.TO_TEST.value, "ææµ"),27 (OperateIDEnum.TO_ONLINE.value, "ä¸çº¿"),28 (OperateIDEnum.TO_OFFLINE.value, "ä¸æ¶"),29 (OperateIDEnum.IN_TEST.value, "æ£å¨ææµ"),30 (OperateIDEnum.IN_ONLINE.value, "æ£å¨ä¸çº¿"),31 (OperateIDEnum.IN_OFFLINE.value, "æ£å¨ä¸æ¶"),32 (OperateIDEnum.REGISTER_INFO.value, "åºæ¬ä¿¡æ¯æ³¨å"),33 (OperateIDEnum.CREATE_DB.value, "æ°æ®åºå建"),34 (OperateIDEnum.INITIAL_CVS.value, "SVN代ç åå§å"),35 (OperateIDEnum.GRANT_DB_AUTH.value, "æ°æ®åºææ"),36 (OperateIDEnum.INITIAL_APP_CODE.value, "åå§åAPP代ç "),37 (OperateIDEnum.DELETE_APP.value, "å é¤APP"),38]39APP_ALL_OPERATE_ID_LIST = [OperateIDEnum.TO_TEST.value,40 OperateIDEnum.TO_ONLINE.value,41 OperateIDEnum.TO_OFFLINE.value,42 OperateIDEnum.IN_TEST.value,43 OperateIDEnum.IN_ONLINE.value,44 OperateIDEnum.IN_OFFLINE.value]45APP_TEST_OPERATE_ID_LIST = [OperateIDEnum.TO_TEST.value, OperateIDEnum.IN_TEST.value]46APP_ONLINE_OPERATE_ID_LIST = [OperateIDEnum.TO_ONLINE.value, OperateIDEnum.IN_ONLINE.value]47APP_OFFLINE_OPERATE_ID_LIST = [OperateIDEnum.TO_OFFLINE.value, OperateIDEnum.IN_OFFLINE.value]48APP_DID_OPERATE_ID_LIST = [OperateIDEnum.TO_TEST.value,49 OperateIDEnum.TO_ONLINE.value,50 OperateIDEnum.TO_OFFLINE.value]51APP_ONGOING_OPERATE_ID_LIST = [OperateIDEnum.IN_TEST.value,52 OperateIDEnum.IN_ONLINE.value,53 OperateIDEnum.IN_OFFLINE.value]54class StatusEnum(Enum):55 SUCCESS = True56 FAIL = False57# ç¨æ·æä½ç±»å58class UserOperateTypeEnum(Enum):59 APP_CREATE = 160 APP_DELETE = 261 RELEASE_TEST = 362 RELEASE_ONLINE = 463 RELEASE_OFFLINE = 564USER_OPERATE_TYPE_CHOICES = [65 (UserOperateTypeEnum.APP_CREATE.value, "APPå建"),66 (UserOperateTypeEnum.APP_DELETE.value, "å é¤APP"),67 (UserOperateTypeEnum.RELEASE_TEST.value, "APPææµ"),68 (UserOperateTypeEnum.RELEASE_ONLINE.value, "APPä¸çº¿"),69 (UserOperateTypeEnum.RELEASE_OFFLINE.value, "APPä¸æ¶"),70]71# app engine eventç¶æ72class EventStatusEnum(Enum):73 READY = "READY"74 PENDING = "PENDING"75 FAILURE = "FAILURE"76 SUCCESS = "SUCCESS"77class OperateCodeEnum(Enum):78 """79 åå¸è®°å½ç±»å80 """81 ALL = "0"82 TEST = "1"83 ONLINE = "2"84 OFFLINE = "3"85OPERATE_CODE_LIST = [86 OperateCodeEnum.ALL.value,87 OperateCodeEnum.TEST.value,88 OperateCodeEnum.ONLINE.value,89 OperateCodeEnum.OFFLINE.value90]91class EventResultEnum(Enum):92 FAIL = 093 SUCCESS = 194 PENDING = 295class DeployPageTypeEnum(Enum):96 TEST = "test_form"97 ONLINE = "online_form"98 OFFLINE = "offline_form"99# é¨ç½²æ ¡éªæ¶çé误100DEPLOY_ERROR_DICT = {101 "20000": "æ¿æ´»ç é误, 请确认æ¿æ´»ç ç³è¯·æ¶app_codeå¡«åæ£ç¡®, å¯éæ°ç³è¯·ç¶åå¨[åºç¨ç®¡ç-åºæ¬ä¿¡æ¯]ä¸ç¼è¾æ´æ°",102 "20001": "app_codeåæ¿æ´»ç ä¸å¹é
! 请确认æ¿æ´»ç ç³è¯·æ¶app_codeå¡«åæ£ç¡®, å¯éæ°ç³è¯·ç¶åå¨[åºç¨ç®¡ç-åºæ¬ä¿¡æ¯]ä¸ç¼è¾æ´æ°",103 "20002": "é¨ç½²ç¯å¢å¯¹åºæºå¨çmacå°åä¸æ¿æ´»ç ä¸å¹é
! 请确认æ¿æ´»ç ç³è¯·æ¶ææagentæºå¨çmacå°åå¡«åæ£ç¡®, å¯éæ°ç³è¯·ç¶åå¨[åºç¨ç®¡ç-åºæ¬ä¿¡æ¯]ä¸ç¼è¾æ´æ°",104 "20100": "PaaS Agent æå¡å¨ ID æè
TOKEN ä¸æ£ç¡®! 请确认[å¼åè
ä¸å¿-æå¡å¨ä¿¡æ¯]ä¸æ³¨åçAgentæå¡å¨ ID å TOKENä¸å®é
Agenté¨ç½²é
ç½®ä¸è´",105 "20101": "PaaS Agent License æææ§è¿æ",106 "20102": "PaaS Agent License macå°åæ误",107 "20103": "PaaS Agent License 解æ失败",108 "20104": "PaaS Agent License è¯ä¹¦æ件ä¸åå¨",109 "20300": "第ä¸æ¹æå¡ RabbitMQ ç³è¯·èµæºå¤±è´¥, 请确认 RabbitMQ å¯ç¨",...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!