Beispiel #1
0
def jumpLogin(self):
    driver = self.driver
    try:
        # 文件中读取cookie
        conf = Configs()
        file_path = conf.getCookieFilePath()  # 获取cookie.txt文件目录

        f = open(file_path, 'r')
        s = f.readline()
        f.close()
        c = re.split(',', s)
        cookie = {'name': c[0], 'value': c[1]}
        # 添加cookie信息
        driver.add_cookie({
            'name': cookie.get('name'),
            'value': cookie.get('value')
        })
        driver.get(self.base_url)
        es = driver.find_elements_by_xpath('//*[@id="root"]/div/div[1]/ul/li')
        es[0].click()  # 判断是否已跳过登录,若没有则此处会报错,进而调用登录模块
    except:
        login.login(self)  # 调用登录模块
        time.sleep(0.5)
        ckl = driver.get_cookies()  # 将最新cookie写入cookie.txt文件
        for ckd in ckl:  # 注:(ckl:为列表,其中放的字典;ck_c:为字典)
            pass
        s = ckd['name'] + ',' + ckd['value']  # 拼接cookie信息
        f = open(file_path, 'w')  # 写入最新cookie的name和value
        f.write(s)
        f.close()
Beispiel #2
0
class Aa(unittest.TestCase):
    def setUp(self):
        self.logger = Logs.getLogger()
        self.conf = Configs()
        self.driver = self.conf.getDriver()  # 浏览器对象
        self.base_url = self.conf.getURL()  # 获取URL
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()
        self.verificationErrors = []
        self.accept_next_alert = True
        self.logger.info('初始化测试模板完成')

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)
        self.logger.info('清理测试模板完成')

    # 测试名字
    # @unittest.skip("跳过这条用例执行")    # 跳过这个用例
    def test_template(self):
        u"""测试模板"""
        log = self.logger
        log.info('测试测试模板')
        driver = self.driver
        driver.get(self.base_url)
        jumplogin.jumpLogin(self)  # 跳过登录,跳过验证码,若已有cookie信息已过期则调用等模块
        log.info('已跳过登录')
        joinscm.joinScm(self)  # 进入scm
        joinscm.joinScmIframe(self)  # 跳入scm_iframe
        log.info('已进入scm_iframe')
        """========开始测试内容====================================================="""
        log.info('开始进行测试')

        sleep(5)
Beispiel #3
0
def load_configs(current_directory):
    from utils.configs import Configs

    configs = Configs()
    configs.load_configs(os.path.join(current_directory, '..', 'sample_configs', 'tests.config'))

    return configs
Beispiel #4
0
def setUpModule():
    print("整个文件开始时执行\n")
    global driver_a, logger_a, conf_a
    conf_a = Configs()              # 实例化配置对象
    driver_a = conf_a.getDriver()   # 获得Driver
    driver_a.implicitly_wait(20)
    driver_a.maximize_window()
    logger_a = Logs.getLogger()     # 获得日志
Beispiel #5
0
def load_configs(current_directory):
    from utils.configs import Configs

    configs = Configs()
    configs.load_configs(
        os.path.join(current_directory, '..', 'sample_configs',
                     'tests.config'))

    return configs
class BreakageManage(unittest.TestCase):
    def setUp(self):
        self.logger = Logs.getLogger()
        self.conf = Configs()
        self.driver = self.conf.getDriver()  # 浏览器对象
        self.base_url = self.conf.getURL()  # 获取URL
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()
        self.verificationErrors = []
        self.accept_next_alert = True
        self.logger.info('初始化报损管理完成')

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)
        self.logger.info('清理报损管理完成')

    # 报损管理_查询
    # @unittest.skip("跳过这条用例执行")    # 跳过这个用例
    def test_A_breakageManage_see(self):
        u"""scm报损管理_查询"""
        log = self.logger
        log.info('测试报损管理_查询')
        driver = self.driver
        driver.get(self.base_url)
        jumplogin.jumpLogin(self)  # 跳过登录,跳过验证码,若已有cookie信息已过期则调用等模块
        log.info('已跳过登录')
        joinscm.joinScm(self)  # 进入scm
        joinscm.joinScmIframe(self)  # 跳入scm_iframe
        log.info('已进入scm_iframe')
        """========开始测试内容====================================================="""
        log.info('开始报损管理_查询测试')
        # 定位“报损管理”
        breakageManage = BreakageManagePage(driver)
        log.info('已进入报损管理模块')
        # 获取测试用例数据(需要传入测试用例数据文件再各环境中的测试目录)
        rf = ExcelReader(
            r'\scm_warehouse_manage\BreakageManage\BreakageManageSee_data.xlsx'
        )
        see_values = rf.getTestData  # 调用此方法时不需要加括号
        log.info('以获取报损管理_查询测试数据')
        i = 1
        at = Asserts()  # 创建断言对象
        for v in see_values:
            log.info('第 %d 组测试数据' % i)
            i += 1
            breakageManage.optionWarehouse(v.get('warehouseCode'))
            breakageManage.optionAuditState(v.get('auditStatus'))
            breakageManage.optionStockRemovalState(v.get('outStatus'))
            breakageManage.inputBreakageNumber(v.get('BreakageNumber'))
            breakageManage.clickSee()
            sleep(1)
            es = breakageManage.getBreakageNumbers()
            at.assertTexts(es, v.get('BreakageNumber'), '报损管理_查询', driver)
            breakageManage.joinBreakageManage()
            sleep(0.5)
Beispiel #7
0
 def setUp(self):
     self.logger = Logs.getLogger()
     self.conf = Configs()
     self.driver = self.conf.getDriver()  # 浏览器对象
     self.base_url = self.conf.getURL()  # 获取URL
     self.driver.implicitly_wait(30)
     self.driver.maximize_window()
     self.verificationErrors = []
     self.accept_next_alert = True
     self.logger.info('初始化采购管理完成')
Beispiel #8
0
 def __init__(self, in_test_data_catalog, sheet=0, title_line=True):
     # 初始化测试用例数据根目录,精确到每个环境的根目录
     conf = Configs()
     self.file_path = conf.getDataPath()
     excel_path = self.file_path + '\\' + in_test_data_catalog
     if os.path.exists(excel_path):
         self.excel = excel_path
     else:
         raise FileNotFoundError('文件不存在!')
     self.sheet = sheet
     self.title_line = title_line
     self._data = list()
    def test_not_enough_honor(self):
        '''Tests a robot with few honors, trying to give birth.'''
        population_control = PopulationControl()
        database = MemcachedDatabase()
        configs = Configs()

        robot = database.get_robot(TestGiveBirth.ROBOT_ID, for_update=True)
        robot.set_honor(configs.get_robots_birth_required_honor() - 1)
        database.commit()

        with self.assertRaises(NotEnoughHonorError):
            population_control.execute_command("123", "give_birth", [TestGiveBirth.ROBOT_ID])

        database.rollback()
    def test_info(self):
        '''Test received information.'''
        action = InfoAction()
        world = World()
        configs = Configs()
        robot = Robot("test_info_action_1293", "123")

        info = action.do_action(robot, [robot.get_id()])

        self.assertEqual(info['world_size'], '{0},{1}'.format(*world.get_size()))
        self.assertEqual(info['plant_max_age'], configs.get_plant_max_age())
        self.assertEqual(info['plant_matured_age'], configs.get_plant_matured_age())
        self.assertEqual(info['action_delay'], configs.get_robots_actions_delay())
        self.assertEqual(info['birth_required_honor'], configs.get_robots_birth_required_honor())
Beispiel #11
0
    def __init__(self):
        self._authenticator = Authenticator()
        self._database = MemcachedDatabase()

        configs = Configs()
        self._robots_action_delay = configs.get_robots_actions_delay() / 1000

        self._actions = {'status': StatusAction(),
                         'sense': SenseAction(),
                         'move': MoveAction(),
                         'plant': PlantAction(),
                         'pick_water': PickWaterAction(),
                         'info': InfoAction(),
                         'eat': EatAction(),
                         'water': WaterAction()}
Beispiel #12
0
    def test_not_enough_honor(self):
        '''Tests a robot with few honors, trying to give birth.'''
        population_control = PopulationControl()
        database = MemcachedDatabase()
        configs = Configs()

        robot = database.get_robot(TestGiveBirth.ROBOT_ID, for_update=True)
        robot.set_honor(configs.get_robots_birth_required_honor() - 1)
        database.commit()

        with self.assertRaises(NotEnoughHonorError):
            population_control.execute_command("123", "give_birth",
                                               [TestGiveBirth.ROBOT_ID])

        database.rollback()
Beispiel #13
0
 def findReport(self):
     print('寻找最新测试报告')
     self.log.info('寻找最新测试报告')
     # 找文件路径
     conf = Configs()  # 实例化配置对象
     result_dir = conf.getReportPath()  # 获取报告存放路径
     lists = os.listdir(result_dir)  # 获取目录中的所有文件列表
     lists.sort(key=lambda fn: os.path.getatime(result_dir + "\\" + fn)
                if not os.path.isdir(result_dir + "\\" + fn) else 0)
     print('最新测试报告为:' + lists[-1])
     self.log.info('已找到最新测试报告')
     # 【os.path.join()】:join()方法用来连接字符串,通过路径与文件名的拼接,我们将得到目录下最新被创建的的文件名的完整路径。
     file_new = os.path.join(result_dir, lists[-1])  # 获取最新文件的完整路径
     self.log.info('已获取最新测试报告文件绝对路径')
     print('最新测试报告路径为:', file_new)
     return file_new
Beispiel #14
0
    def __init__(self):
        if (self.__initialized): return
        self.__initialized = True

        # check whether running in beaker
        self.server = self.get_delivered_param("RUN_SERVER")
        if self.server == "":
            # Run by rhsm config file
            self.confs = Configs(RHSM_CONF)
            self.server = self.confs._confs["server"]
            if self.server == "sam":
                self.samhostip = self.confs._confs["samhostip"]
                self.samhostname = self.confs._confs["samhostname"]
                self.configure_sam_host(self.samhostname, self.samhostip)
            elif self.server == "stage":
                stage_name = self.confs._confs["stagename"]
                self.configure_stage_host(stage_name)
            elif self.server == "candlepin":
                pass
        else:
            if self.server == "sam":
                # Run by delivered param
                self.samhostip = self.get_delivered_param("SAM_IP")
                self.samhostname = self.get_delivered_param("SAM_HOSTNAME")
                self.configure_sam_host(self.samhostname, self.samhostip)
            elif self.server == "stage":
                stage_name = self.get_delivered_param("STAGE_NAME")
                self.configure_stage_host(stage_name)
            elif self.server == "candlepin":
                pass
    def initialize(self):
        '''Initializes the database by setting required key-values.'''
        self._hooks = []

        mc = MemcachedConnection()
        mc.config_connection(Configs().get_server_database_port())

        mc_connection = mc.get_connection()
        mc_connection.add("all_robots", [])
Beispiel #16
0
def initialize_process(
):  # pragma: no cover - This will be mocked in the tests an never runs.
    '''Initializes the newly forked process'''
    config_file_path = os.environ.get("BINARY_SKY_CONFIG_FILE")
    logging_config_path = os.environ.get("BINARY_SKY_LOGGING_FILE")

    Configs().load_configs(config_file_path)
    Logger().load_configs(logging_config_path)
    MemcachedDatabase().initialize()
    def test_ok(self):
        '''Tests a valid situation.'''
        population_control = PopulationControl()
        database = MemcachedDatabase()
        configs = Configs()

        robot = database.get_robot(TestGiveBirth.ROBOT_ID, for_update=True)
        robot.set_honor(configs.get_robots_birth_required_honor() + 1)
        database.commit()

        new_password = population_control.execute_command("123", "give_birth", [TestGiveBirth.ROBOT_ID])
        database.commit()

        updated_robot = database.get_robot(TestGiveBirth.ROBOT_ID, for_update=False)

        self.assertEqual(updated_robot.get_honor(), 1)
        self.assertTrue(isinstance(new_password, str))
        self.assertEqual(len(new_password), 16)
Beispiel #18
0
    def __init__(self, id, password, name=""):
        super(Robot, self).__init__()

        if not isinstance(name, str) or len(name) > MAX_ROBOT_NAME:
            raise LongRobotNameError("Robot name cannot be longer than {0}".format(MAX_ROBOT_NAME))

        configs = Configs()

        self._id = id
        self._name = name
        self._alive = True
        self._password = password
        self._x = 0
        self._y = 0
        self._has_water = False
        self._energy = configs.get_robots_initial_energy()
        self._maximum_energy = configs.get_robots_maximum_energy()
        self._life = configs.get_robots_initial_life()
        self._honor = 0
        self._last_executed_action_time = 0
Beispiel #19
0
    def test_ok(self):
        '''Tests a valid situation.'''
        population_control = PopulationControl()
        database = MemcachedDatabase()
        configs = Configs()

        robot = database.get_robot(TestGiveBirth.ROBOT_ID, for_update=True)
        robot.set_honor(configs.get_robots_birth_required_honor() + 1)
        database.commit()

        new_password = population_control.execute_command(
            "123", "give_birth", [TestGiveBirth.ROBOT_ID])
        database.commit()

        updated_robot = database.get_robot(TestGiveBirth.ROBOT_ID,
                                           for_update=False)

        self.assertEqual(updated_robot.get_honor(), 1)
        self.assertTrue(isinstance(new_password, str))
        self.assertEqual(len(new_password), 16)
Beispiel #20
0
 def __init__(self):
     if (self.__initialized): return
     self.__initialized = True
     self.confs = Configs(RHSM_GUI_CONF)
     self.server = self.confs._confs["server"]
     if self.server == "sam":
         self.configure_sam_host(self.confs._confs["samhostname"],
                                 self.confs._confs["samhostip"])
     elif self.server == "stage":
         self.configure_stage_host(self.confs._confs["stage_name"])
     elif self.server == "candlepin":
         pass
    def __init__(self):
        self._world = World()
        configs = Configs()

        self._result = {
            'world_size': '{0},{1}'.format(*self._world.get_size()),
            'plant_max_age': configs.get_plant_max_age(),
            'plant_matured_age': configs.get_plant_matured_age(),
            'action_delay': configs.get_robots_actions_delay(),
            'maximum_energy': configs.get_robots_maximum_energy(),
            'birth_required_honor': configs.get_robots_birth_required_honor()
        }
    def __init__(self):
        self._world = World()
        configs = Configs()

        self._result = {'world_size': '{0},{1}'.format(*self._world.get_size()),
                        'plant_max_age': configs.get_plant_max_age(),
                        'plant_matured_age': configs.get_plant_matured_age(),
                        'action_delay': configs.get_robots_actions_delay(),
                        'maximum_energy': configs.get_robots_maximum_energy(),
                        'birth_required_honor': configs.get_robots_birth_required_honor()}
Beispiel #23
0
class Authenticator:

    def __init__(self):
        self._database = MemcachedDatabase()
        self._configs = Configs()

    def authenticate_robot(self, robot_object, password):
        '''Authenticate the robot access and its password.'''

        # Ensuring that password is a string.
        if not isinstance(password, str):
            raise AuthenticationFailedError("Wrong password for Robot {0}".format(robot_object.get_id()))

        if password != robot_object.get_password():
            raise AuthenticationFailedError("Wrong password for Robot {0}".format(robot_object.get_id()))

        if not robot_object.get_alive():
            raise AuthenticationFailedError("Robot {0} is dead!".format(robot_object.get_id()))

    def authenticate_new_robot(self, password):
        '''Authenticate if this password is valid for a new robot to join the game
        (e.g. born).
        It remove the password from the database. i.e. the password can use for
        only one born.

        @raise InvalidPasswordError: If password wasn't valid.
        '''
        self._database.pop_password(password)

    def authenticate_admin(self, password):
        '''Authenticates an admin. Admins are the ones who can see
        things like world statistics.
        '''
        admin_password = self._configs.get_server_admin_password()

        if admin_password is None or admin_password.isspace():
            raise AuthenticationFailedError("Invalid Admin password.")

        if not isinstance(password, str):
            raise AuthenticationFailedError("Invalid Admin password.")

        if admin_password != password:
            raise AuthenticationFailedError("Invalid Admin password.")
Beispiel #24
0
class Logs(object):
    """只能创建为单例"""
    __instance = None  # 私有的类属性(instance:实例)
    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance  # 返回上一次创建对象的引用

    logger = None
    # 日志级别
    levels = {"n": logging.NOTSET,
              "d": logging.DEBUG,
              "i": logging.INFO,
              "w": logging.WARN,
              "e": logging.ERROR,
              "c": logging.CRITICAL}

    log_level = "d"                     # 设置最低日志级别
    log_max_byte = 10 * 1024 * 1024     # 设定日志文件最大内存
    log_backup_count = 5                # 当第一个文件写满后最大备份日志文件数
    conf = Configs()                    # 创建配置对象
    log_path = conf.getLogPath()        # 获取不同环境下的日志路径
    log_file = log_path + r'\scm_test.log'


    @staticmethod
    def getLogger():

        if Logs.logger is not None:
            return Logs.logger

        Logs.logger = logging.Logger("oggingmodule.FinalLogger")
        log_handler = logging.handlers.RotatingFileHandler(filename=Logs.log_file,
                                                           maxBytes=Logs.log_max_byte,
                                                           backupCount=Logs.log_backup_count,
                                                           encoding='UTF-8')
        log_fmt = logging.Formatter("%(asctime)s-【scm测试日志 :--%(levelname)s :--%(message)s :--%(filename)s:%(lineno)d")
        log_handler.setFormatter(log_fmt)
        Logs.logger.addHandler(log_handler)
        Logs.logger.setLevel(Logs.levels.get(Logs.log_level))
        return Logs.logger
    def test_eating_matured(self):
        '''Tests when robot eat a matured plant.'''
        world = World()
        database = MemcachedDatabase()
        action_manager = ActionManager()
        plant = Plant()
        plant.set_age(Configs().get_plant_matured_age() + 1)

        world.plant(plant, TestEatAction.LOCATION)
        database.commit()

        robot = database.get_robot(TestEatAction.ROBOT_ID, for_update=True)
        robot.set_energy(10)
        database.commit()

        action_manager.do_action("123", "eat", [TestEatAction.ROBOT_ID])
        database.commit()

        updated_robot = database.get_robot(TestEatAction.ROBOT_ID)
        self.assertGreater(updated_robot.get_energy(), robot.get_energy())
Beispiel #26
0
    def test_info(self):
        '''Test received information.'''
        action = InfoAction()
        world = World()
        configs = Configs()
        robot = Robot("test_info_action_1293", "123")

        info = action.do_action(robot, [robot.get_id()])

        self.assertEqual(info['world_size'],
                         '{0},{1}'.format(*world.get_size()))
        self.assertEqual(info['plant_max_age'], configs.get_plant_max_age())
        self.assertEqual(info['plant_matured_age'],
                         configs.get_plant_matured_age())
        self.assertEqual(info['action_delay'],
                         configs.get_robots_actions_delay())
        self.assertEqual(info['birth_required_honor'],
                         configs.get_robots_birth_required_honor())
Beispiel #27
0
class PurchaseManage(unittest.TestCase):
    def setUp(self):
        self.logger = Logs.getLogger()
        self.conf = Configs()
        self.driver = self.conf.getDriver()  # 浏览器对象
        self.base_url = self.conf.getURL()  # 获取URL
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()
        self.verificationErrors = []
        self.accept_next_alert = True
        self.logger.info('初始化采购管理完成')

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)
        self.logger.info('清理采购管理完成')

    # 订单管理_查询
    # @unittest.skip("跳过这条用例执行")    # 跳过这个用例
    def test_A_OrderManageSee(self):
        u"""scm订单管理_查询"""
        log = self.logger
        log.info('测试订单管理_查询')
        driver = self.driver
        driver.get(self.base_url)
        jumplogin.jumpLogin(self)  # 跳过登录,跳过验证码,若已有cookie信息已过期则调用等模块
        log.info('已跳过登录')
        joinscm.joinScm(self)  # 进入scm
        joinscm.joinScmIframe(self)  # 跳入scm_iframe
        log.info('已进入scm_iframe')
        """========开始测试内容====================================================="""
        log.info('开始订单管理_查询测试')
        # 定位“订单管理”
        orderManage = OrderManagePage(driver)
        log.info('已进入订单管理页面')
        # 获取测试用例数据(需要传入测试用例数据文件再各环境中的测试目录)
        rf = ExcelReader(r'\scm_PurchaseManage\OrderManageSee_data.xlsx')
        see_values = rf.getTestData  # 调用此方法时不需要加括号
        log.info('以获取订单管理_查询测试数据')
        i = 1
        at = Asserts()  # 创建断言对象
        for v in see_values:
            log.info('第 %d 组测试数据' % i)
            i += 1
            orderManage.inputOrderNumber(v.get('OrderNumber'))
            orderManage.optionWarehouse(v.get('Warehouse'))
            orderManage.optionStorageLocation(v.get('StorageLocation'))
            orderManage.inputSupplier(v.get('Supplier'))
            orderManage.optionInventoryState(v.get('InventoryState'))
            orderManage.inputBuyer(v.get('Buyer'))
            orderManage.optionOrderState(v.get('OrderState'))
            orderManage.clickSee()
            sleep(1)
            log.info('开始断言')
            es1 = orderManage.getOrderBasicInfors()
            at.assertValueInTexts(es1, v.get('OrderNumber'), '订单管理查询_采购单号',
                                  driver)
            at.assertValueInTexts(es1, v.get('Warehouse'), '订单管理查询_仓库', driver)
            at.assertValueInTexts(es1, v.get('StorageLocationAssert'),
                                  '订单管理查询_库位', driver)
            at.assertValueInTexts(es1, v.get('Supplier'), '订单管理查询_供应商', driver)
            es2 = orderManage.getStates()
            at.assertValueInTexts(es2, v.get('InventoryState'), '订单管理查询_入库状态',
                                  driver)
            at.assertValueInTexts(es2, v.get('OrderState'), '订单管理查询_订单状态',
                                  driver)
            es3 = orderManage.getOthers()
            at.assertValueInTexts(es3, v.get('Buyer'), '订单管理查询_采购员', driver)
            log.info('断言通过')
            orderManage.joinOrderManagePage()

    # 退货管理_查询
    # @unittest.skip("跳过这条用例执行")    # 跳过这个用例
    def test_B_SalesReturnManageSee(self):
        u"""scm退货管理_查询"""
        log = self.logger
        log.info('测试退货管理_查询')
        driver = self.driver
        driver.get(self.base_url)
        jumplogin.jumpLogin(self)  # 跳过登录,跳过验证码,若已有cookie信息已过期则调用等模块
        log.info('已跳过登录')
        joinscm.joinScm(self)  # 进入scm
        joinscm.joinScmIframe(self)  # 跳入scm_iframe
        log.info('已进入scm_iframe')
        """========开始测试内容====================================================="""
        log.info('开始退货管理_查询测试')
        # 定位“退货管理”
        salesReturnManage = SalesReturnManagePage(driver)
        log.info('已进入退货管理页面')
        # 获取测试用例数据(需要传入测试用例数据文件再各环境中的测试目录)
        rf = ExcelReader(r'\scm_PurchaseManage\OrderManageSee_data.xlsx')
        see_values = rf.getTestData  # 调用此方法时不需要加括号
        log.info('以获取退货管理_查询测试数据')
        i = 1
        at = Asserts()  # 创建断言对象
        for v in see_values:
            log.info('第 %d 组测试数据' % i)
            i += 1
    def test_robot_simulation(self):
        '''This test simulates a full game scenario.'''
        database = MemcachedDatabase()
        world = World()
        configs = Configs()

        print()
        print("Simulating a robot playing the game. This may take a while.")

        # Creating a world for the robot to live in.
        # The world map is:
        #
        #    000000
        #    000222
        #    000144
        #    000144

        row01 = [MapSquare(MapSquareTypes.SOIL, (0, 30)),
                 MapSquare(MapSquareTypes.SOIL, (1, 30)),
                 MapSquare(MapSquareTypes.SOIL, (2, 30)),
                 MapSquare(MapSquareTypes.SOIL, (3, 30)),
                 MapSquare(MapSquareTypes.SOIL, (4, 30)),
                 MapSquare(MapSquareTypes.SOIL, (5, 30))]
        row02 = [MapSquare(MapSquareTypes.SOIL, (0, 31)),
                 MapSquare(MapSquareTypes.SOIL, (1, 31)),
                 MapSquare(MapSquareTypes.SOIL, (2, 31)),
                 MapSquare(MapSquareTypes.ROCK, (3, 31)),
                 MapSquare(MapSquareTypes.ROCK, (4, 31)),
                 MapSquare(MapSquareTypes.ROCK, (5, 31))]
        row03 = [MapSquare(MapSquareTypes.SOIL, (0, 32)),
                 MapSquare(MapSquareTypes.SOIL, (1, 32)),
                 MapSquare(MapSquareTypes.SOIL, (2, 32)),
                 MapSquare(MapSquareTypes.SAND, (3, 32)),
                 MapSquare(MapSquareTypes.WATER, (4, 32)),
                 MapSquare(MapSquareTypes.WATER, (5, 32))]
        row04 = [MapSquare(MapSquareTypes.SOIL, (0, 33)),
                 MapSquare(MapSquareTypes.SOIL, (1, 33)),
                 MapSquare(MapSquareTypes.SOIL, (2, 33)),
                 MapSquare(MapSquareTypes.SAND, (3, 33)),
                 MapSquare(MapSquareTypes.WATER, (4, 33)),
                 MapSquare(MapSquareTypes.WATER, (5, 33))]

        database.add_square_row(row01)
        database.add_square_row(row02)
        database.add_square_row(row03)
        database.add_square_row(row04)

        # Creating parent of our robot.
        parent_robot = Robot("parent_robot_1982.345", "123", name="Parent")
        parent_robot.set_honor(configs.get_robots_birth_required_honor() + 1)
        world.add_robot(parent_robot, (2, 31))
        database.commit()

        # Giving birth to our hero.
        result = self.post_request({'command': 'give_birth',
                                    'password': '******',
                                    'args': ["parent_robot_1982.345"]})
        self.assertEqual(result['status'], 200, result)
        born_password = result['result']

        # Robot requests a born.
        result = self.post_request({'command': 'born',
                                    'password': born_password,
                                    'args': [parent_robot.get_id()]})
        self.assertEqual(result['status'], 200)
        robot_id = result['result']['robot_id']
        password = result['result']['password']

        # Getting status.
        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['alive'])
        self.assertFalse(result['result']['has_water'])
        self.assertEqual(result['result']['location'], "2,30")

        # Moving somewhere to plan a corp.
        # Note that parent robot is on the south. So, we have to turn around it.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'W']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'S']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'S']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)

        # We are at the location. Checking if its correct.
        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['location'], "2,32")

        # Planting a corp here.
        result = self.post_request({'command': 'plant',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        # Checking if it is planted.
        result = self.post_request({'command': 'sense',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['2,32']['surface_type'], MapSquareTypes.SOIL)
        self.assertIsNotNone(result['result']['2,32']['plant'])

        # Going to pick water.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'pick_water',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['has_water'])

        # Getting back to the plant location.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'W']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'W']})
        self.assertEqual(result['status'], 200, result)

        # Watering
        result = self.post_request({'command': 'water',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        # Checking
        result = self.post_request({'command': 'sense',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        # It lost some water already.
        self.assertGreater(result['result']['2,32']['plant']['water_level'], 70)

        # Plant should be matured by now. Eating!
        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        previous_energy = result['result']['energy']

        result = self.post_request({'command': 'eat',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertGreater(result['result']['energy'], previous_energy)

        # Now, trying some bad moves!

        # Trying to plant on a sand.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'plant',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'CannotPlantHereError')

        # Trying to move to a rock.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'N']})
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'LocationIsBlockedError')
class ObjectUpdater(DatabaseHook):
    '''This class checks objects in the world, and updates them
    if required.

    Responsibilities of this class:
        * Killing and removing a robot from the world, if its
          energy reached zero or it ran out of life.
        * Removing a plant from the world if its water level
          reached zero or it became too old.
        * Maturing a plant if it reached a certain age.
        * Updating a plant's water level during time.
    '''

    def __init__(self):
        self._database = MemcachedDatabase()
        self._configs = Configs()

    def robot_got(self, robot_object, locked_for_update):
        '''Checks and updates the specified robot's object.'''
        if robot_object.get_energy() <= 0 or robot_object.get_life() <= 0:

            if not locked_for_update:
                # This would call this method again, and robot will be updated.
                return self._database.get_robot(robot_object.get_id(), for_update=True)

            robot_object.set_alive(False)

            # Removing the robot from its location.
            try:
                square = self._database.get_square(robot_object.get_location(), for_update=True)
            except LockAlreadyAquiredError:
                # Trying one more time.
                time.sleep(0.02)
                square = self._database.get_square(robot_object.get_location(), for_update=True)

            square.set_robot_id(None)

            # XXX: Though it's a very dirty thing to do, we have to commit these changes, because
            #      later this robot will face an Authentication Exception, and our changes will be
            #      lost.
            self._database.commit()

            # Immediately, locking the robot object. It's not atomic, so there's a little chance
            # that concurrency happens. But, it shouldn't be a problem, since the robot is already
            # dead, and can't do anything anyway.
            self._database.get_lock(robot_object.get_id())

        return robot_object

    def square_got(self, location, square_object, locked_for_update):
        '''Checks and updates specified square object.'''
        plant = square_object.get_plant()

        if plant is None:
            return square_object

        # Time passed from the last time this plant updated.
        last_update = time.time() - plant.get_last_update()
        passed_cycles = math.floor(last_update / (self._configs.get_plant_cylce() / 1000))

        if passed_cycles <= 0:
            # No cycle passed, no need to be updated.
            return square_object

        if not locked_for_update:
            # This will call this method again.
            try:
                return self._database.get_square(location, for_update=True)
            except LockAlreadyAquiredError:
                # Trying one more time.
                time.sleep(0.02)
                return self._database.get_square(location, for_update=True)

        plant.set_age(plant.get_age() + passed_cycles)
        plant.set_water_level(plant.get_water_level() - (passed_cycles * self._configs.get_plant_lose_water_in_cycle()))

        if plant.get_age() > self._configs.get_plant_max_age() or plant.get_water_level() <= 0:
            # Plant is dead! Removing it from the world.
            square_object.set_plant(None)

        plant.set_last_update(time.time())

        return square_object
Beispiel #30
0
def load_configs(config_file):
    configs = Configs()
    configs.load_configs(config_file)

    return configs
 def __init__(self):
     self._database = MemcachedDatabase()
     self._configs = Configs()
Beispiel #32
0
import os
import torch
from torch import optim
from torch.utils.data import DataLoader
from utils.loss import HDRLoss
from utils.HDRutils import tonemap
from utils.dataprocessor import dump_sample
from dataset.HDR import KalantariTestDataset
from models.NHDRRNet import NHDRRNet
from utils.configs import Configs


# Get configurations
configs = Configs()

# Load dataset
test_dataset = KalantariTestDataset(configs=configs)
test_dataloader = DataLoader(test_dataset, batch_size=1, shuffle=True)

# Build NHDRRNet model from configs
model = NHDRRNet()
if configs.multigpu is False:
    device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    model.to(device)
else:
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    if device == torch.device('cpu'):
        raise EnvironmentError('No GPUs, cannot initialize multigpu training.')
    model.to(device)

# Define optimizer
class OtherOutbound(unittest.TestCase):
    def setUp(self):
        self.logger = Logs.getLogger()
        self.conf = Configs()
        self.driver = self.conf.getDriver()  # 浏览器对象
        self.base_url = self.conf.getURL()  # 获取URL
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()
        self.verificationErrors = []
        self.accept_next_alert = True
        self.logger.info('初始化其他出库完成')

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)
        self.logger.info('清理其他出库完成')

    # 其他出库_查询
    # @unittest.skip("跳过这条用例执行")    # 跳过这个用例
    def test_A_OtherOutboundSee(self):
        u"""scm其他出库_查询"""
        log = self.logger
        log.info('测试其他出库_查询')
        driver = self.driver
        driver.get(self.base_url)
        jumplogin.jumpLogin(self)  # 跳过登录,跳过验证码,若已有cookie信息已过期则调用等模块
        log.info('已跳过登录')
        joinscm.joinScm(self)  # 进入scm
        joinscm.joinScmIframe(self)  # 跳入scm_iframe
        log.info('已进入scm_iframe')
        """========开始测试内容====================================================="""
        log.info('开始其他出库_查询测试')
        # 定位“其他出库”
        otherOutbound = OtherOutboundPage(driver)
        log.info('已进入损益管理模块')
        # 获取测试用例数据(需要传入测试用例数据文件再各环境中的测试目录)
        rf = ExcelReader(
            r'\scm_warehouse_manage\OtherOutbound\OtherOutboundSee_data.xlsx')
        see_values = rf.getTestData  # 调用此方法时不需要加括号
        log.info('以获取损益管理_查询测试数据')
        i = 1
        at = Asserts()  # 创建断言对象
        for v in see_values:
            log.info('第 %d 组测试数据' % i)
            i += 1
            otherOutbound.optionWarehouse(v.get('Warehouse'))
            otherOutbound.optionCheckState(v.get('CheckState'))
            otherOutbound.optionStockRemovalState(v.get('StockRemovalState'))
            otherOutbound.inputOtherOrderNumber(v.get('OtherOrderNumber'))
            otherOutbound.clickSee()
            sleep(1)
            log.info('开始断言')
            es1 = otherOutbound.getOtherOrderNumbers()
            at.assertValueInTexts(es1, v.get('OtherOrderNumber'), '其他出库查询_单号',
                                  driver)
            es2 = otherOutbound.getCheckStates()
            at.assertValueInTexts(es2, v.get('CheckState'), '其他出库查询_审核状态',
                                  driver)
            es3 = otherOutbound.getStockRemovalStates()
            at.assertValueInTexts(es3, v.get('StockRemovalState'),
                                  '其他出库查询_出库状态', driver)
            es4 = otherOutbound.getWarehouses()
            at.assertValueInTexts(es4, v.get('Warehouse'), '其他出库查询_仓库', driver)
            log.info('断言通过')
            otherOutbound.joinOtherOutbound()
class ObjectUpdater(DatabaseHook):
    '''This class checks objects in the world, and updates them
    if required.

    Responsibilities of this class:
        * Killing and removing a robot from the world, if its
          energy reached zero or it ran out of life.
        * Removing a plant from the world if its water level
          reached zero or it became too old.
        * Maturing a plant if it reached a certain age.
        * Updating a plant's water level during time.
    '''
    def __init__(self):
        self._database = MemcachedDatabase()
        self._configs = Configs()

    def robot_got(self, robot_object, locked_for_update):
        '''Checks and updates the specified robot's object.'''
        if robot_object.get_energy() <= 0 or robot_object.get_life() <= 0:

            if not locked_for_update:
                # This would call this method again, and robot will be updated.
                return self._database.get_robot(robot_object.get_id(),
                                                for_update=True)

            robot_object.set_alive(False)

            # Removing the robot from its location.
            try:
                square = self._database.get_square(robot_object.get_location(),
                                                   for_update=True)
            except LockAlreadyAquiredError:
                # Trying one more time.
                time.sleep(0.02)
                square = self._database.get_square(robot_object.get_location(),
                                                   for_update=True)

            square.set_robot_id(None)

            # XXX: Though it's a very dirty thing to do, we have to commit these changes, because
            #      later this robot will face an Authentication Exception, and our changes will be
            #      lost.
            self._database.commit()

            # Immediately, locking the robot object. It's not atomic, so there's a little chance
            # that concurrency happens. But, it shouldn't be a problem, since the robot is already
            # dead, and can't do anything anyway.
            self._database.get_lock(robot_object.get_id())

        return robot_object

    def square_got(self, location, square_object, locked_for_update):
        '''Checks and updates specified square object.'''
        plant = square_object.get_plant()

        if plant is None:
            return square_object

        # Time passed from the last time this plant updated.
        last_update = time.time() - plant.get_last_update()
        passed_cycles = math.floor(last_update /
                                   (self._configs.get_plant_cylce() / 1000))

        if passed_cycles <= 0:
            # No cycle passed, no need to be updated.
            return square_object

        if not locked_for_update:
            # This will call this method again.
            try:
                return self._database.get_square(location, for_update=True)
            except LockAlreadyAquiredError:
                # Trying one more time.
                time.sleep(0.02)
                return self._database.get_square(location, for_update=True)

        plant.set_age(plant.get_age() + passed_cycles)
        plant.set_water_level(plant.get_water_level() -
                              (passed_cycles *
                               self._configs.get_plant_lose_water_in_cycle()))

        if plant.get_age() > self._configs.get_plant_max_age(
        ) or plant.get_water_level() <= 0:
            # Plant is dead! Removing it from the world.
            square_object.set_plant(None)

        plant.set_last_update(time.time())

        return square_object
 def __init__(self):
     self._database = MemcachedDatabase()
     self._configs = Configs()
    def test_robot_simulation(self):
        '''This test simulates a full game scenario.'''
        database = MemcachedDatabase()
        world = World()
        configs = Configs()

        print()
        print("Simulating a robot playing the game. This may take a while.")

        # Creating a world for the robot to live in.
        # The world map is:
        #
        #    000000
        #    000222
        #    000144
        #    000144

        row01 = [
            MapSquare(MapSquareTypes.SOIL, (0, 30)),
            MapSquare(MapSquareTypes.SOIL, (1, 30)),
            MapSquare(MapSquareTypes.SOIL, (2, 30)),
            MapSquare(MapSquareTypes.SOIL, (3, 30)),
            MapSquare(MapSquareTypes.SOIL, (4, 30)),
            MapSquare(MapSquareTypes.SOIL, (5, 30))
        ]
        row02 = [
            MapSquare(MapSquareTypes.SOIL, (0, 31)),
            MapSquare(MapSquareTypes.SOIL, (1, 31)),
            MapSquare(MapSquareTypes.SOIL, (2, 31)),
            MapSquare(MapSquareTypes.ROCK, (3, 31)),
            MapSquare(MapSquareTypes.ROCK, (4, 31)),
            MapSquare(MapSquareTypes.ROCK, (5, 31))
        ]
        row03 = [
            MapSquare(MapSquareTypes.SOIL, (0, 32)),
            MapSquare(MapSquareTypes.SOIL, (1, 32)),
            MapSquare(MapSquareTypes.SOIL, (2, 32)),
            MapSquare(MapSquareTypes.SAND, (3, 32)),
            MapSquare(MapSquareTypes.WATER, (4, 32)),
            MapSquare(MapSquareTypes.WATER, (5, 32))
        ]
        row04 = [
            MapSquare(MapSquareTypes.SOIL, (0, 33)),
            MapSquare(MapSquareTypes.SOIL, (1, 33)),
            MapSquare(MapSquareTypes.SOIL, (2, 33)),
            MapSquare(MapSquareTypes.SAND, (3, 33)),
            MapSquare(MapSquareTypes.WATER, (4, 33)),
            MapSquare(MapSquareTypes.WATER, (5, 33))
        ]

        database.add_square_row(row01)
        database.add_square_row(row02)
        database.add_square_row(row03)
        database.add_square_row(row04)

        # Creating parent of our robot.
        parent_robot = Robot("parent_robot_1982.345", "123", name="Parent")
        parent_robot.set_honor(configs.get_robots_birth_required_honor() + 1)
        world.add_robot(parent_robot, (2, 31))
        database.commit()

        # Giving birth to our hero.
        result = self.post_request({
            'command': 'give_birth',
            'password': '******',
            'args': ["parent_robot_1982.345"]
        })
        self.assertEqual(result['status'], 200, result)
        born_password = result['result']

        # Robot requests a born.
        result = self.post_request({
            'command': 'born',
            'password': born_password,
            'args': [parent_robot.get_id()]
        })
        self.assertEqual(result['status'], 200)
        robot_id = result['result']['robot_id']
        password = result['result']['password']

        # Getting status.
        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['alive'])
        self.assertFalse(result['result']['has_water'])
        self.assertEqual(result['result']['location'], "2,30")

        # Moving somewhere to plan a corp.
        # Note that parent robot is on the south. So, we have to turn around it.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'W']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'S']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'S']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)

        # We are at the location. Checking if its correct.
        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['location'], "2,32")

        # Planting a corp here.
        result = self.post_request({
            'command': 'plant',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        # Checking if it is planted.
        result = self.post_request({
            'command': 'sense',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['2,32']['surface_type'],
                         MapSquareTypes.SOIL)
        self.assertIsNotNone(result['result']['2,32']['plant'])

        # Going to pick water.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'pick_water',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['has_water'])

        # Getting back to the plant location.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'W']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'W']
        })
        self.assertEqual(result['status'], 200, result)

        # Watering
        result = self.post_request({
            'command': 'water',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        # Checking
        result = self.post_request({
            'command': 'sense',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        # It lost some water already.
        self.assertGreater(result['result']['2,32']['plant']['water_level'],
                           70)

        # Plant should be matured by now. Eating!
        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        previous_energy = result['result']['energy']

        result = self.post_request({
            'command': 'eat',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertGreater(result['result']['energy'], previous_energy)

        # Now, trying some bad moves!

        # Trying to plant on a sand.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'plant',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'CannotPlantHereError')

        # Trying to move to a rock.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'N']
        })
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'LocationIsBlockedError')
Beispiel #37
0
 def __init__(self):
     # 得到相应截图目录
     conf = Configs()
     self.path = conf.getScreenshotPath()
Beispiel #38
0
 def setUp(self):
     self.log = Logs.getLogger()
     self.verificationErrors = []
     self.accept_next_alert = True
     self.conf = Configs()  # 创建配置对象
     self.log.info('登录测试初始化完成')
Beispiel #39
0
class Login(unittest.TestCase):
    def setUp(self):
        self.log = Logs.getLogger()
        self.verificationErrors = []
        self.accept_next_alert = True
        self.conf = Configs()  # 创建配置对象
        self.log.info('登录测试初始化完成')

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)
        self.log.info('清理登录完成')

    # scm登录测试
    # @unittest.skip("跳过这条用例执行")    # 跳过这个用例
    def test_A_login(self):
        u"""scm登录测试"""
        log = self.log
        log.info('测试登录')
        data_path = self.conf.getDataPath()  # 获取登录测试数据路径
        file_path = data_path + r'\scm_login\login_data.txt'
        path = self.conf.getScreenshotPath()  # 获取截图路径
        f = open(file_path, "r")
        log.info('已获得测试数据文件')
        ups = []
        try:
            lines = f.readlines()  # 一次性读取整个文件,并安行为单位分成列表
            for line in lines:
                li = re.split(',', line)
                ups.append(li)
        finally:
            f.close()
        log.info('已获得测试数据')
        i = 1
        for up in ups:
            log.info('第 %d 组测试数据' % i)
            i = i + 1
            self.driver = self.conf.getDriver()  # 浏览器对象
            self.base_url = self.conf.getURL()  # 获取URL
            driver = self.driver
            driver.get(self.base_url)
            log.info('已进入登录页面')
            # 调用登录模块
            login.login_test(self, up[0], up[1], up[2])
            time.sleep(2)
            log.info('已调用登录模块,断言登录')
            # 判断是否登录是否正确
            now_time = time.strftime("%Y%m%d-%H%M%S", time.localtime())
            try:
                e = driver.find_element_by_xpath(
                    '//*[@id="root"]/div/div[1]/div[2]/span')
                at = Asserts()  # 创建断言对象
                at.assertText(e, up[3], '账号不匹截图', driver)  # text断言一个元素
            except:
                driver.get_screenshot_as_file(path + '\\' + up[4] + '[' +
                                              now_time + '].png')  # 截图操作
                print('登录失败截图成功')
                print(path)
            log.info('断言通过')
            time.sleep(1)
            driver.quit()