Exemplo n.º 1
0
class Crops(dict):
    switch_template = HD.loadTemplates('crops', 'switch*')

    def __init__(self, device, tasklist):
        self.log = MyLogger('Crops', LOG_LEVEL=logging.INFO)
        self.device = device
        self.tasklist = tasklist
        self.data = []
        self.settings = []
        self.updateListData()

    def updateListData(self):
        settings = HD.loadJSON('crops')
        resources = HD.loadJSON('resources')
        count = {}
        if len(resources) and "crops" in resources and len(settings):
            if resources['crops'] != self.data or settings != self.settings:
                self.log.error("Changes found")
                self.log.error(settings)
                self.log.error(self.settings)
                self.log.error(resources['crops'])
                self.log.error(self.data)
                self.data = resources['crops']
                self.settings = settings
                for crop in self.values():
                    crop.enabled = False
                for newcrop in self.data:
                    crop = newcrop['crop']
                    if crop not in count:
                        count[crop] = 0
                    count[crop] += 1
                    name = f"Crop {crop} [{count[crop]}]"
                    if crop in self.settings:
                        if name not in self:
                            self[name] = Crop(self.device, self.tasklist, crop)
                        data = self.settings[crop].copy()
                        data.update(newcrop)
                        data['name'] = name
                        data['log'] = self.log
                        data['enabled'] = True
                        self.log.debug(f"location: {newcrop['location']}")
                        data['position'] = self.device.getPos(
                            newcrop['location'])
                        self.log.debug(f"position: {data['position']}")
                        data['temp_switch'] = self.switch_template
                        data['update'] = self.updateListData
                        for key, value in data.items():
                            setattr(self[name], key, value)
Exemplo n.º 2
0
class Shop(HD):
    def __init__(self, device, tasklist):
        HD.__init__(self, device, tasklist, 'money')
        self.log=MyLogger('shop', LOG_LEVEL=logging.DEBUG)
        self.tasklist.addtask(20, f"checking for items to sell", self.image, self.checkItems)
        self.shoplist=Shoplist(self)
        self.position=HD.getPos([-15,0])
        self.slots=4
        self.max_slots=4
        self.atshop=False
        self.temp_shop=self.device.loadTemplates('shop','')

    def add(self, product, min_amount=6,sell=False):
        self.products.append(ShopItem(product, min_amount))

    def checkItems(self):
        self.atshop=False
        wait=10
        if self.max_slots>self.slots:
            self.checkShop()
            self.atshop=True
        try:
            json_data=HD.loadJSON('sell')
            for product,data in data.items():
                wished,scheduled=self.tasklist.getWish(product)

                #check if prodruct needs to be ordered
                if (scheduled-wished<data['maximum']-self.slots*data['amount']) and data['order']:
                    self.log.debug(f'need more {product}')
                    self.tasklist.addWish(product,data['maximum']-(scheduled-wished))

                if -wished>data['minimum']+data['amount']:
                    available=-wished-data['minimum']
                    stocks=int(available/data['amount'])
                    if stocks<self.slots:
                        self.slots-= stocks
                    else:
                        stocks=self.slots
                        self.slots=0
                    if stocks:
                        self.log.debug(f'i can sell some')
                        self.shoplist.add(product,stocks, **data)
                        wait=2
        except Exception as e:
            self.log.error(e)
        finally:
            self.tasklist.addtask(wait, f"checking for items to sell", self.image, self.checkItems)
            self.sellItems()

    def sellItems(self):
        self.log.debug('selling items')
        try:
            if not len(shoplist):
                raise Exception("No items to sell")
            if not self.atshop or self.open_shop():
                raise Exception("Shop is not open")
            spots=self.device.locate_item(self.temp_create, 0.85)
            for product,data in self.shoplist.items():
                if product in self.temp_products:
                    while self.shoplist[product].stock:
                        if not len(spots):
                            raise Exception("No free spot to sell items"):
                        location=spots.pop()
                        self.device.tap(location)
                        location=self.device.locate_item(self.temp_products[product],.85, one=True)
                        if not len(location):
                            raise Exception("Could not find product in list")
                        self.device.tap(location)
                        self.log.debug('item should be selected by now')





            if not len(locations):
                raise



        except Exception as e:
            self.log.error(e)

    def checkShop(self):
        self.log.debug('checking Shop')
        try:
            if not self.open_shop():
                raise Exception("Shop is not open")
            locations=self.device.locate_item(self.temp_sold, 0.85)
            if not len(locations):
                raise Exception("Could not find sold items")
            for location in locations:
                self.device.tap(location)
        except Exception as e:
            self.log.error(e)

    def open_shop(self):
        try:
            self.move_to()
            location = self.device.locate_item(self.temp_shop, .85, one = True)
            if not len(location):
                raise Exception("Could not locate shop")
            self.device.tap(location)
            self.atshop=True
            return True
        except Exception as e:
            self.log.error('OPEN SHOP')
            self.log.error(e)
            return False
Exemplo n.º 3
0
class CalcucatorPositiveTestcase(unittest.TestCase, MyLogger):
    def __parse_config(self, config_path):
        config = configparser.ConfigParser()
        config.read(config_path)
        self.config = config

    @property
    def __app_link(self):
        return self.config['TEST_LINK'].get('AppLink')

    @property
    def __screenshot_dirpath(self):
        return self.config['LOGGER'].get('ScreenshotDirPath', 'screenshots')

    def setUp(self):  # Данный метод выполняется перед каждым тестом
        self.__parse_config('./config.ini')
        self.driver = webdriver.Chrome()
        self.driver.get(self.__app_link)
        self.calculator = WebCalculator(self.driver)
        self.log = MyLogger('TestCaseLog').logger()

    def log_fail(self, error_msg, step_name):
        dt = datetime.datetime.today()
        curr_time_format = dt.strftime("%Y-%m-%d-%H.%M.%S")
        screenshot_path = os.path.join(
            self.__screenshot_dirpath,
            '{}{}.png'.format(step_name, curr_time_format))
        self.driver.save_screenshot(screenshot_path)
        self.log.error(error_msg)
        self.fail()

    # Основные сценарии

    def test_bruteforce(self):  # Проверка нажатия всех кнопок
        commands = [
            self.calculator.key_1_XPath, self.calculator.key_2_XPath,
            self.calculator.key_3_XPath, self.calculator.key_4_XPath,
            self.calculator.key_5_XPath, self.calculator.key_6_XPath,
            self.calculator.key_7_XPath, self.calculator.key_8_XPath,
            self.calculator.key_9_XPath, self.calculator.key_0_XPath
        ]
        try:
            self.calculator.execute_commands(commands)
        except Exception as e:
            self.log_fail('Тест: test_bruteforce не пройден {}'.format(e),
                          'test_bruteforce_FAIL_')

    def test_addition(self):  # Проверка операции сложения на примере 1 + 5 = 6
        commands = [
            self.calculator.key_1_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_5_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '6'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_addition не пройден {}'.format(e),
                          'test_addition_FAIL_')

    def test_subtraction(
            self):  # Проверка операции вычетанеия на примере 9 - 5 = 4
        commands = [
            self.calculator.key_9_XPath, self.calculator.key_subtraction_XPath,
            self.calculator.key_5_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '4'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_subtraction не пройден {}'.format(e),
                          'test_subtraction_FAIL_')

    def test_multiplication(
            self):  # Проверка операции умножения на примере 3 х 4 = 12

        commands = [
            self.calculator.key_3_XPath,
            self.calculator.key_multiplication_XPath,
            self.calculator.key_4_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '12'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_multiplication не пройден {}'.format(e),
                          'test_multiplication_FAIL_')

    def test_division(self):  # Проверка операции деления на примере 8 / 4 = 2
        commands = [
            self.calculator.key_8_XPath, self.calculator.key_division_XPath,
            self.calculator.key_4_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '2'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_division не пройден {}'.format(e),
                          'test_division_FAIL_')

    def test_clear(self):  # Проверка операции очистки AC
        commands = [
            self.calculator.key_1_XPath, self.calculator.key_2_XPath,
            self.calculator.key_3_XPath, self.calculator.key_5_XPath,
            self.calculator.key_clear_XPath
        ]
        expected_res = '0'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_clear не пройден {}'.format(e),
                          'test_clear_FAIL_')

    def test_point(self):  # Проверка простановки точки для дробных чисел(.)
        commands = [
            self.calculator.key_1_XPath, self.calculator.key_2_XPath,
            self.calculator.key_3_XPath, self.calculator.key_point_XPath,
            self.calculator.key_3_XPath, self.calculator.key_2_XPath,
            self.calculator.key_1_XPath
        ]
        expected_res = '123.321'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_point не пройден {}'.format(e),
                          'test_point_FAIL_')

    def test_change_sign(self):  # Проверка изменения знака числа (+/-)
        commands = [
            self.calculator.key_5_XPath,
            self.calculator.key_5_XPath,
            self.calculator.key_5_XPath,
            self.calculator.key_change_sign_XPath,
        ]
        expected_res = '-555'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_change_sign не пройден {}'.format(e),
                          'test_change_sign_FAIL_')

    def test_percent(
            self):  # Проверка расчета процента для числа 100 % от 100 = 1
        commands = [
            self.calculator.key_1_XPath,
            self.calculator.key_0_XPath,
            self.calculator.key_0_XPath,
            self.calculator.key_percent_XPath,
        ]
        expected_res = '1'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail('Тест: test_percent не пройден {}'.format(e),
                          'test_percent_FAIL_')

    # Комбинаторика основных сценариев сценарии (в данном случае кейсы расписываются из условия, что после первого действия автоматом считается резщультат )

    def test_addition_combination(
        self
    ):  # Проверка операции сложения, после другого математического действия, например 3 - 1 + 5 = 7
        commands = [
            self.calculator.key_3_XPath, self.calculator.key_subtraction_XPath,
            self.calculator.key_1_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_5_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '7'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_addition_combination не пройден {}'.format(e),
                'test_addition_combination_FAIL_')

    def test_subtraction_combination(
        self
    ):  # Проверка операции вычетанеия, после другого математического действия, например 9 + 9 - 7 = 11
        commands = [
            self.calculator.key_9_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_9_XPath, self.calculator.key_subtraction_XPath,
            self.calculator.key_7_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '11'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_subtraction_combination не пройден {}'.format(e),
                'test_subtraction_combination_FAIL_')

    def test_multiplication_combination(
        self
    ):  # Проверка операции умножения, после другого математического действия, например (3 + 4) х 2 = 14

        commands = [
            self.calculator.key_3_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_4_XPath,
            self.calculator.key_multiplication_XPath,
            self.calculator.key_2_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '14'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_multiplication_combination не пройден {}'.format(
                    e), 'test_multiplication_combination_FAIL_')

    def test_division_combination(
        self
    ):  # Проверка операции деления, после другого математического действия, например (6 + 6) / 4 = 3
        commands = [
            self.calculator.key_6_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_6_XPath, self.calculator.key_division_XPath,
            self.calculator.key_4_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '3'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_division_combination не пройден {}'.format(e),
                'test_division_combination_FAIL_')

    def test_clear_combination(
        self
    ):  # Проверка операции очистки AC, после математического действия, например (1 + 1) AC 4 = 4
        commands = [
            self.calculator.key_1_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_1_XPath, self.calculator.key_clear_XPath,
            self.calculator.key_4_XPath
        ]
        expected_res = '4'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_clear_combination не пройден {}'.format(e),
                'test_clear_combination_FAIL_')

    def test_point_combination(
        self
    ):  # Проверка простановки точки для дробных чисел(.), после математического действия, например 1 + 1.5 = 2.5
        commands = [
            self.calculator.key_1_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_1_XPath, self.calculator.key_point_XPath,
            self.calculator.key_5_XPath, self.calculator.key_equality_XPath
        ]
        expected_res = '2.5'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_point_combination не пройден {}'.format(e),
                'test_point_combination_FAIL_')

    def test_change_sign_combination(
        self
    ):  # Проверка изменения знака числа (+/-), после математического действия, например 5 + (-1) = 4
        commands = [
            self.calculator.key_5_XPath, self.calculator.key_addition_XPath,
            self.calculator.key_1_XPath, self.calculator.key_change_sign_XPath,
            self.calculator.key_equality_XPath
        ]
        expected_res = '4'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_change_sign_combination не пройден {}'.format(e),
                'test_change_sign_combination_FAIL_')

    def test_percent_combination(
        self
    ):  # Проверка расчета процента в математическом действии, например 100 - 30% = 70
        commands = [
            self.calculator.key_1_XPath, self.calculator.key_0_XPath,
            self.calculator.key_0_XPath, self.calculator.key_subtraction_XPath,
            self.calculator.key_3_XPath, self.calculator.key_0_XPath,
            self.calculator.key_percent_XPath,
            self.calculator.key_equality_XPath
        ]
        expected_res = '70'
        try:
            self.calculator.execute_commands(commands)
            assert self.calculator.find_node(
                self.calculator.key_result_XPath).text == expected_res
        except Exception as e:
            self.log_fail(
                'Тест: test_percent_combination не пройден {}'.format(e),
                'test_percent_combination_FAIL_')

    def tearDown(self):  # После каждого теста закрываем окно браузера
        self.driver.quit()
Exemplo n.º 4
0
        except Exception, e:
            logger.error("connect() except {0}".format(e))
            return

        try:
            self.socketio_namespace.on('connect', self.onConnect)
            self.socketio_namespace.on('disconnect', self.onDisconnect)
            self.socketio_namespace.on('reconnect', self.onReconnect)
            logger.info("socketio.on() success")
        except Exception, e:
            logger.error("socketio.on() except {0}".format(e))

        try:
            self.socketio.wait(seconds=1)
        except Exception, e:
            logger.error("wait() except {0}".format(e))

        logger.info("Connected.")

    def _async_emit(self, event, data={'data': 0}):
        try:
            self.connect()
            if self.socketio:
                self.socketio_namespace.emit(event, data)
                self.disconnect()
        except Exception, e:
            logger.error("_async_emit() except {0}".format(e))

    def emit(self, event, data={'data': 0}):
        logger.info("emit to server: {} - {}".format(event, str(data)))
        try:
Exemplo n.º 5
0
        default=False)

    args = parser.parse_args()

    if not args.noinit:
        running_logger.info("Initialisation starts")
        running_logger.info("apk folder: %s", args.apk_file)
        running_logger.info("appium port:%s", args.appium_port)
        running_logger.info("appium back port:%s", args.appium_back_port)
        running_logger.info("appium system port:%s", args.appium_back_port)
        running_logger.info("proxy port:%s", args.proxy_port)

        finished, result_folder = init(args)

        if not finished:
            running_logger.error("Initialisation Fail, result folder: %s",
                                 result_folder)
            exit()
    else:
        manifest = Manifest(args.apk_file)
        package_name = manifest.get_package_name()
        launcher_activity = manifest.get_launcher_activity()
        version = manifest.get_version_name()
        result_folder = os.path.join(
            args.result_folder,
            package_name + '_' + version + '_' + args.idp_name)

    running_logger.info("Main program starts")
    running_logger.info("apk folder: %s", args.apk_file)
    running_logger.info("appium port:%s", args.appium_port)
    running_logger.info("appium back port:%s", args.appium_back_port)
    running_logger.info("appium system port:%s", args.appium_back_port)
Exemplo n.º 6
0
                        default=None)
    parser.add_argument('--reset',
                        action='store_true',
                        dest='reset',
                        help='use reset function if this flag is set')
    parser.add_argument(
        '--noappium',
        action='store_true',
        dest='noappium',
        help='do not start appium and new device in this program,\
                            environment has been set up by default')
    args = parser.parse_args()

    # check working dir// because brother wolf hardcoded something
    if os.path.basename(os.getcwd()) != 'tool_testing':
        running_logger.error('Working dir must be tool_testing')
        running_logger.error('exit!')
        exit(-1)

    # make sure apk exists
    if not os.path.isfile(args.apk_file):
        running_logger.error("Cannot find the apk file")
        running_logger.error("exit!")
        exit(-1)

    # logging
    running_logger.info('Initialisation starts')
    running_logger.info('apk:\t\t\t%s', args.apk_file)
    running_logger.info('appium port:\t\t%s', args.appium_port)
    running_logger.info('appium back port:\t%s', args.appium_back_port)
    running_logger.info('proxy port:\t\t%s', args.proxy_port)