コード例 #1
0
    def _apply(self,
               put: unittest.TestCase,
               actual_phase_2_step_2_recorded_value,
               message_builder: asrt.MessageBuilder):
        put.assertIsInstance(actual_phase_2_step_2_recorded_value, dict,
                             'actual value should be a dictionary')

        for phase in sorted(self.expected_phase_2_step_2_recorded_value.keys(),
                            key=attrgetter('value')):
            put.assertIn(phase, self.expected_phase_2_step_2_recorded_value)
            expected_steps = self.expected_phase_2_step_2_recorded_value[phase]
            actual = actual_phase_2_step_2_recorded_value[phase]
            for expected_step in sorted(expected_steps.keys()):
                put.assertIn(expected_step, actual, 'Phase {}: Missing step: {}'.format(phase, expected_step))
                put.assertEqual(expected_steps[expected_step],
                                actual[expected_step],
                                '{}/{}'.format(phase, expected_step))
                put.assertEqual(len(expected_steps),
                                len(actual),
                                'Actual number of recorded steps for phase {} must not exceed expected'.format(phase))
                put.assertEqual(len(self.expected_phase_2_step_2_recorded_value),
                                len(actual_phase_2_step_2_recorded_value),
                                'Actual number of recorded phases must not exceed expected')
                # To be sure that above code does not miss any case
                put.assertEqual(self.expected_phase_2_step_2_recorded_value,
                                actual_phase_2_step_2_recorded_value,
                                'Recordings per phase and step')
コード例 #2
0
    def run_rdb_assertions(
            cls,
            test_case: unittest.TestCase,
            retriever: Retriever,
            definition: specification.ThresholdSpecification
    ):
        test_case.assertIsInstance(retriever, threshold.disk.RDBThresholdRetriever)

        data: pandas.DataFrame = retriever.retrieve()

        test_case.assertEqual(sorted([column for column in data.keys()]), ['name', 'site_no', 'value'])
        test_case.assertEqual(len(data.site_no.unique()), 2)
        test_case.assertEqual(len(data.index.unique()), 366)
        test_case.assertEqual(data.index.name, 'threshold_day')

        created_thresholds = threshold.get_thresholds(definition)

        test_case.assertEqual(len(data.site_no.unique()), len(created_thresholds))

        for key, thresholds in created_thresholds.items():
            test_case.assertIn(key, data.site_no.unique())
            for threshold_name, group_data in data[data.site_no == key].groupby(['name']):
                matching_thresholds = [
                    thresh
                    for thresh in thresholds
                    if thresh.name == threshold_name
                ]
                test_case.assertEqual(len(matching_thresholds), 1)
                matching_threshold = matching_thresholds[0]
                test_case.assertIn(threshold_name, definition)
                threshold_definition = definition[threshold_name]
                test_case.assertEqual(threshold_definition.weight, matching_threshold.weight)
コード例 #3
0
    def _apply(self, put: unittest.TestCase,
               actual_phase_2_step_2_recorded_value,
               message_builder: asrt.MessageBuilder):
        put.assertIsInstance(actual_phase_2_step_2_recorded_value, dict,
                             'actual value should be a dictionary')

        for phase in sorted(self.expected_phase_2_step_2_recorded_value.keys(),
                            key=attrgetter('value')):
            put.assertIn(phase, self.expected_phase_2_step_2_recorded_value)
            expected_steps = self.expected_phase_2_step_2_recorded_value[phase]
            actual = actual_phase_2_step_2_recorded_value[phase]
            for expected_step in sorted(expected_steps.keys()):
                put.assertIn(
                    expected_step, actual,
                    'Phase {}: Missing step: {}'.format(phase, expected_step))
                put.assertEqual(expected_steps[expected_step],
                                actual[expected_step],
                                '{}/{}'.format(phase, expected_step))
                put.assertEqual(
                    len(expected_steps), len(actual),
                    'Actual number of recorded steps for phase {} must not exceed expected'
                    .format(phase))
                put.assertEqual(
                    len(self.expected_phase_2_step_2_recorded_value),
                    len(actual_phase_2_step_2_recorded_value),
                    'Actual number of recorded phases must not exceed expected'
                )
                # To be sure that above code does not miss any case
                put.assertEqual(self.expected_phase_2_step_2_recorded_value,
                                actual_phase_2_step_2_recorded_value,
                                'Recordings per phase and step')
コード例 #4
0
ファイル: waveforms_tests.py プロジェクト: qutech-lab/qupulse
def assert_constant_consistent(test_case: unittest.TestCase, wf: Waveform):
    if wf.is_constant():
        cvs = wf.constant_value_dict()
        test_case.assertEqual(wf.defined_channels, cvs.keys())
        for ch in wf.defined_channels:
            test_case.assertEqual(cvs[ch], wf.constant_value(ch))
    else:
        test_case.assertIsNone(wf.constant_value_dict())
        test_case.assertIn(None, {wf.constant_value(ch) for ch in wf.defined_channels})
コード例 #5
0
def step_impl(context, dino):
    rows = context.driver.find_elements_by_tag_name('tr')
    #dinos = []
    dinos = [row.find_elements_by_tag_name('td')[1].text for row in rows[1:]]
    #for row in rows[1:]:
    #    tds = row.find_elements_by_tag_name('td')
    #    dinos.append(tds[1].text)
    test = TestCase()
    test.assertIn(dino, dinos)
コード例 #6
0
def step_impl(context, nombre_dino):
    rows = context.driver.find_elements_by_tag_name('tr')
    dinosaurios = []
    for row in rows[1:]:
        td_dino = row.find_elements_by_tag_name('td')
        dinosaurios.append(td_dino[1].text)
    context.td_dino = td_dino
    test = TestCase()
    test.assertIn(nombre_dino, dinosaurios)
コード例 #7
0
ファイル: symbol_table.py プロジェクト: emilkarlen/exactly
def _assert_table_contains(put: unittest.TestCase,
                           table: sut.SymbolTable,
                           expected_symbol: NameAndValue):
    put.assertTrue(table.contains(expected_symbol.name),
                   'table SHOULD contain the value')
    put.assertIn(expected_symbol.name,
                 table.names_set,
                 'names set should contain the value')
    put.assertIs(expected_symbol.value,
                 table.lookup(expected_symbol.name),
                 'lookup should fins the value')
コード例 #8
0
ファイル: symbol_table.py プロジェクト: emilkarlen/exactly
def _assert_table_contains(put: unittest.TestCase,
                           table: sut.SymbolTable,
                           expected_symbol: NameAndValue[ASymbolTableValue]):
    put.assertTrue(table.contains(expected_symbol.name),
                   'table SHOULD contain the value')
    put.assertIn(expected_symbol.name,
                 table.names_set,
                 'names set should contain the value')
    put.assertIs(expected_symbol.value,
                 table.lookup(expected_symbol.name),
                 'lookup should fins the value')
コード例 #9
0
ファイル: environment.py プロジェクト: emilkarlen/exactly
    def _apply(
        self,
        put: unittest.TestCase,
        value: List[str],
        message_builder: MessageBuilder,
    ):
        key_msg = message_builder.apply('key')
        val_msg = message_builder.apply('value')

        actual_as_dict = self._dict_from_lines(value)

        for ek, ev in self.expected_sub_set.items():
            put.assertIn(ek, actual_as_dict, key_msg)
            put.assertEqual(ev, actual_as_dict[ek], val_msg)
コード例 #10
0
ファイル: test.py プロジェクト: johnchinjew/hangmen
def check_player_state(test: unittest.TestCase,
                       state: dict,
                       pid: str,
                       name: str,
                       word: str = '',
                       ready: bool = False,
                       alive: bool = True):
    for attr in ['id', 'name', 'word', 'ready', 'alive']:
        test.assertIn(attr, state)
    if pid is not None:
        test.assertEqual(state['id'], pid)
    test.assertEqual(state['word'], word)
    test.assertEqual(state['ready'], ready)
    test.assertEqual(state['alive'], alive)
コード例 #11
0
def assert_expected_output_file_contents(
        testcase: unittest.TestCase, filename: str,
        expected_data: Mapping[int, Sequence[str]]) -> None:
    testcase.assertTrue(os.path.exists(filename))
    remaining_lines = None
    with open(filename, 'r') as csv_file:
        # First line should contain the header
        testcase.assertIn('unix.timestamp', csv_file.readline())
        remaining_lines = csv_file.readlines()

    testcase.assertIsNotNone(remaining_lines)
    testcase.assertEqual(len(expected_data), len(remaining_lines))
    for data_points, line in zip(expected_data.values(), remaining_lines):
        for word in data_points:
            testcase.assertIn(word, line)
コード例 #12
0
    def test_deleteHuds(self):
        TestCase.assertIn(self,
                          self.game.tilemap.layers.by_name['playerHud'],
                          self.game.tilemap.layers)
        TestCase.assertIn(self,
                          'playerHud',
                          self.game.tilemap.layers.by_name)

        # TODO: deleteHuds devrait retourner ce qu'il enleve pour simplifier
        # les tests.
        self.game.deleteHuds()

        TestCase.assertNotIn(self,
                             'playerHud',
                             self.game.tilemap.layers.by_name)
コード例 #13
0
ファイル: test_ask.py プロジェクト: rabbitinspace/rapturebot
def check(obj: unittest.TestCase, question: str,
          choices: Iterable[str]) -> None:
    """
    Убеждаемся, что ответ на вопрос состоит только из указанных вариантов ответа
    """
    limit = 1000
    for choice in choices:
        count = 0
        while count < limit:
            count += 1
            answer = Ask.ask(question)
            obj.assertIn(answer, choices)
            if choice == answer:
                break
        else:  # срабатывает если мы дошли до limit, но так и не встретили choice
            obj.fail(f"'{choice}' not found as answer of '{question}'")
コード例 #14
0
    def run_assertions(
            cls,
            test: unittest.TestCase,
            backend: backends.Backend,
            expected_files: typing.Sequence[str]
    ):
        test.assertEqual(len(backend), len(expected_files))

        for expected_file in expected_files:
            test.assertIn(expected_file, backend)
            raw_data = backend.read(expected_file, store_data=False)

            stream = backend.read_stream(expected_file, store_data=True)
            stream_data = stream.read()
            test.assertEqual(raw_data, stream_data)

            raw_data = backend.read(expected_file)
            test.assertEqual(raw_data, stream_data)
コード例 #15
0
ファイル: test.py プロジェクト: johnchinjew/hangmen
def check_response(test: unittest.TestCase,
                   res: requests.Response,
                   content_type: str = None):
    res_data = None
    if content_type is None:
        test.assertNotIn('Content-Type', res.headers)
    else:
        test.assertIn('Content-Type', res.headers)
        test.assertEqual(res.headers['Content-Type'],
                         content_type + '; charset=utf-8')
        test.assertNotEqual(len(res.text), 0)
        if content_type == 'text/html':
            res_data = res.text
        elif content_type == 'application/json':
            res_data = res.json()
        else:
            raise ValueError()
    return res_data
コード例 #16
0
ファイル: constants.py プロジェクト: ZeroDesigner/pybel
def help_check_hgnc(test_case: unittest.TestCase, namespace_dict) -> None:
    """Assert that the namespace dictionary is correct."""
    test_case.assertIn(HGNC_KEYWORD, namespace_dict)

    test_case.assertIn('MHS2', namespace_dict[HGNC_KEYWORD])
    test_case.assertEqual(set('G'), set(namespace_dict[HGNC_KEYWORD]['MHS2']))

    test_case.assertIn('MIATNB', namespace_dict[HGNC_KEYWORD])
    test_case.assertEqual(set('GR'),
                          set(namespace_dict[HGNC_KEYWORD]['MIATNB']))

    test_case.assertIn('MIA', namespace_dict[HGNC_KEYWORD])
    test_case.assertEqual(set('GRP'), set(namespace_dict[HGNC_KEYWORD]['MIA']))
コード例 #17
0
    def run_single_assertions(cls, test: unittest.TestCase,
                              retriever: Retriever):
        data = retriever.retrieve()

        expected_locations = ("0214655255", "0214657975")

        unique_loaded_locations = data.observation_location.unique()

        for location in expected_locations:
            test.assertIn(location, unique_loaded_locations)

        earliest_possible_date = datetime(year=2015,
                                          month=12,
                                          day=1,
                                          tzinfo=timezone.utc)
        latest_possible_date = datetime(year=2016,
                                        month=1,
                                        day=2,
                                        tzinfo=timezone.utc)
        earliest_date = data.value_date.min()
        latest_date = data.value_date.max()
        test.assertGreater(earliest_date, earliest_possible_date)
        test.assertLess(latest_date, latest_possible_date)

        for location_name, subset in data.groupby(by="observation_location"):
            test.assertGreater(subset.value_date.min(), earliest_possible_date)
            test.assertLess(subset.value_date.max(), latest_possible_date)

            current_date = earliest_date.date()
            present_days = subset.value_date.apply(lambda d: d.date()).unique()
            missing_days = list()

            while current_date <= latest_date:
                if current_date not in present_days:
                    missing_days.append(current_date)
                else:
                    missing_days.clear()

                test.assertLess(len(missing_days), 5)

                current_date += timedelta(days=1)
コード例 #18
0
    def test_to_html(self, variables):
        """LabelTable should not be rendered for variable with more than 100 labels.

        The creation of the HTML of the LabelTable is to time consuming for large
        numbers of labels.
        """

        categories = list()
        for number in range(0, 5):
            categories.append({"label": uuid4(), "value": number})

        test = TestCase()

        mocked_categories = PropertyMock(return_value=categories)
        with patch(
                "ddionrails.data.models.variable.Variable.category_list",
                new_callable=mocked_categories,
        ):
            label_table = LabelTable(variables)
            html_output = label_table.to_html()
            for variable in variables:
                test.assertIn(variable.name, html_output)
コード例 #19
0
def help_check_hgnc(test_case: unittest.TestCase, namespace_dict) -> None:
    """Assert that the namespace dictionary is correct."""
    test_case.assertIn(HGNC_KEYWORD, namespace_dict)

    mhs2 = '7071', 'MHS2'
    test_case.assertIn(mhs2, namespace_dict[HGNC_KEYWORD])
    test_case.assertEqual(set('G'), set(namespace_dict[HGNC_KEYWORD][mhs2]))

    miatnb = '50731', 'MIATNB'
    test_case.assertIn(miatnb, namespace_dict[HGNC_KEYWORD])
    test_case.assertEqual(set('GR'), set(namespace_dict[HGNC_KEYWORD][miatnb]))

    mia = '7076', 'MIA'
    test_case.assertIn(mia, namespace_dict[HGNC_KEYWORD])
    test_case.assertEqual(set('GRP'), set(namespace_dict[HGNC_KEYWORD][mia]))
コード例 #20
0
def test_stress_testing():
    tc = TestCase()

    def check_balance(t):
        tc.assertLess(abs(height(t.left) - height(t.right)), 2, 'Tree is out of balance')

    t = AVLTree()
    vals = list(range(1000))
    random.shuffle(vals)
    for i in range(len(vals)):
        t.add(vals[i])
        for x in vals[:i+1]:
            tc.assertIn(x, t, 'Element added not in tree')
        traverse(t.root, check_balance)

    random.shuffle(vals)
    for i in range(len(vals)):
        del t[vals[i]]
        for x in vals[i+1:]:
            tc.assertIn(x, t, 'Incorrect element removed from tree')
        for x in vals[:i+1]:
            tc.assertNotIn(x, t, 'Element removed still in tree')
        traverse(t.root, check_balance)
コード例 #21
0
def get_valid_key(test: unittest.TestCase, app: App=None) -> str:
    """
    Produce a valid key by using the arobito default credentials against the :py:meth:`App.auth
    <arobito.controlinterface.ControllerBackend.App.auth>` method

    :param test: The currently running unit test case
    :return: A valid key
    """
    if app is None:
        app = create_app(test)

    request_valid = dict(username='******', password='******')
    response = app.auth(request_valid)
    test.assertIsNotNone(response, 'Response is none')
    test.assertIsInstance(response, dict, 'Response is not a dict')
    test.assertIn('auth', response, 'Response does not contain an auth element')
    auth = response['auth']
    test.assertIn('key', auth, 'Auth object does not contain a key')
    key = auth['key']
    test.assertIsNotNone(key, 'Key is None')
    test.assertIsInstance(key, str, 'Key is not a String')
    test.assertRegex(key, '^[a-zA-Z0-9]{64}$', 'Key looks not like expected')
    return key
コード例 #22
0
ファイル: BackendManager.py プロジェクト: arobito/arobito
def evaluate_user_object(test: unittest.TestCase, user_object: dict) -> None:
    """
    Helper function for evaluating an user object

    :param test: The currently running test case
    :param user_object: The user object to evaluate
    """
    test.assertIn("username", user_object, "User name is not in the user object")
    test.assertEqual(user_object["username"], "arobito", 'User name in user object is not "arobito"')
    test.assertIn("level", user_object, "User level is not in user object")
    test.assertEqual(user_object["level"], "Administrator", 'User level is not "Administrator"')
    test.assertIn("timestamp", user_object, "Timestamp is not in user object")
    test.assertIn("last_access", user_object, "Last access timestamp is not in user object")
    test.assertIsInstance(user_object["timestamp"], float, "Timestamp is not a float")
    test.assertIsInstance(user_object["last_access"], float, "Last access is not a float")
    test.assertTrue(
        user_object["timestamp"] <= user_object["last_access"], "Timestamp is not less or equal the last access"
    )
コード例 #23
0
ファイル: test.py プロジェクト: johnchinjew/hangmen
def check_session_state(test: unittest.TestCase,
                        state: dict,
                        sid: str = None,
                        players: list = [],
                        turnOrderContains: list = None,
                        turnOrder: list = None,
                        guessedLetters: str = '',
                        isLobby: bool = True):

    # First check consistency of input
    assert (not ((turnOrderContains is not None) and
                 ((turnOrder is not None))))
    if isLobby:
        if turnOrderContains is not None:
            assert (len(turnOrderContains) == 0)
        if turnOrder is not None:
            assert (len(turnOrder) == 0)
        assert (len(guessedLetters) == 0)

    # Run equality check on state using input
    for attr in ['id', 'players', 'turnOrder', 'alphabet', 'isLobby']:
        test.assertIn(attr, state)
    if sid is not None:
        test.assertEqual(state['id'], sid)
    test.assertEqual(len(state['players']), len(players))
    for pid in players:
        test.assertIn(pid, state['players'])
    # Cannot check ACTUAL turn order (since it is shuffled)
    # only check if they both contain same elements
    if turnOrderContains is not None:
        for pid in turnOrderContains:
            test.assertIn(pid, state['turnOrder'])
    if turnOrder is not None:
        test.assertEqual(state['turnOrder'], turnOrder)
    for c in 'abcdefghjiklmnopqrstuvwxyz':
        test.assertIn(c, state['alphabet']['letters'])
        if c in guessedLetters:
            test.assertTrue(state['alphabet']['letters'][c])
        else:
            test.assertFalse(state['alphabet']['letters'][c])
    test.assertEqual(state['isLobby'], isLobby)
コード例 #24
0
def evaluate_user_object(test: unittest.TestCase, user_object: dict) -> None:
    """
    Helper function for evaluating an user object

    :param test: The currently running test case
    :param user_object: The user object to evaluate
    """
    test.assertIn('username', user_object,
                  'User name is not in the user object')
    test.assertEqual(user_object['username'], 'arobito',
                     'User name in user object is not "arobito"')
    test.assertIn('level', user_object, 'User level is not in user object')
    test.assertEqual(user_object['level'], 'Administrator',
                     'User level is not "Administrator"')
    test.assertIn('timestamp', user_object, 'Timestamp is not in user object')
    test.assertIn('last_access', user_object,
                  'Last access timestamp is not in user object')
    test.assertIsInstance(user_object['timestamp'], float,
                          'Timestamp is not a float')
    test.assertIsInstance(user_object['last_access'], float,
                          'Last access is not a float')
    test.assertTrue(user_object['timestamp'] <= user_object['last_access'],
                    'Timestamp is not less or equal the last access')
コード例 #25
0
ファイル: mako_test.py プロジェクト: melexis/xunit2rst
def test_mako_error_handling():
    ''' Tests error logging and re-raising of an Exception in Mako template by intentionally not passing a variable '''
    kwargs = {
        'report_name': 'my_report',
        'info': ITEST,
        'prefix': 'MAKO_TEST-',
    }
    test_case = TestCase()
    with test_case.assertLogs() as log_cm:
        with assert_raises(TypeError):
            render_template((TEST_OUT_DIR / 'never_created_file.rst'),
                            **kwargs)
    test_case.assertIn(
        'Exception raised in Mako template, which will be re-raised after logging line info:',
        log_cm.output[0])
    test_case.assertIn('File ', log_cm.output[-1])
    test_case.assertIn('line ', log_cm.output[-1])
    test_case.assertIn(
        "in render_body: '% for suite_idx, suite in enumerate(test_suites, start=1):'",
        log_cm.output[-1])
コード例 #26
0
def step_impl(context, dino):
    rows = context.driver.find_elements_by_tag_name('tr')
    dinos = [row.find_elements_by_tag_name('td')[1].text for row in rows[1:]]

    test = TestCase()
    test.assertIn(dino, dinos)
コード例 #27
0
class BasePage(object):
    """
    定一个基类,所有的页面都需要继承此类,会在此类中,封装selenium很大一部分操作页面操作方法
    注意:
    1.所有页面创建的时候,都需要继承与此类
    2.此类中的driver仅仅是变量,在所有页面创建的时候,需要先使用browser_engine.py打开页面,之后方可使用本类中封装的方法
    3.用以上的方法来确保前后操作driver的一致性(重要!)
    """
    def __init__(self, driver):
        self.driver = driver
        self._element_finder = ElementFinder()
        self._test_case = TestCase()

    # 查找元素
    def _element_find(self, locator, first_only, required, tag=None):
        if isinstance(locator, str):
            elements = self._element_finder.find(self.driver, locator, tag)
            if required and len(elements) == 0:
                raise ValueError("Element locator '" + locator +
                                 "' did not match any elements.")
            if first_only:
                if len(elements) == 0:
                    return None
                return elements[0]
        elif isinstance(locator, WebElement):
            elements = locator
        # do some other stuff here like deal with list of webelements
        # ... or raise locator/element specific error if required
        return elements

    # 获取元素的文本
    def _get_text(self, locator):
        element = self._element_find(locator, True, True)
        if element is not None:
            return element.text
        return None

    # 获取元素的值
    def _get_value(self, locator, tag=None):
        element = self._element_find(locator, True, False, tag)
        return element.get_attribute('value') if element is not None else None

    # 获取元素的属性
    def _get_element_attribute(self, locator, attribute_name, tag=None):
        element = self._element_find(locator, True, False, tag)
        return element.get_attribute(attribute_name)

    # 判断元素是否存在
    def _is_element_present(self, locator, tag=None):
        element = self._element_find(locator, True, False, tag=tag)
        if element is not None:
            return True
        return False

    # 打开url操作
    def open_url(self,
                 url=config.URL,
                 implicitly_wait_time=config.IMPLICITLY_WAIT_TIME):
        self.driver.get(url)
        logger.info("open url '%s'" % url)
        self.driver.maximize_window()
        self.set_implicitly_wait_time(implicitly_wait_time)

    # 设置浏览器隐式等待时间
    def set_implicitly_wait_time(
            self, implicitly_wait_time=config.IMPLICITLY_WAIT_TIME):
        self.driver.implicitly_wait(implicitly_wait_time)
        logger.info("set implicitly wait time %s" % implicitly_wait_time)

    # 退出浏览器操作
    def quit_browser(self):
        self.driver.quit()
        logger.info("quit browser")

    # 浏览器前进操作
    def forward(self):
        self.driver.forward()
        logger.info("forward operation")

    # 浏览器后退操作
    def back(self):
        self.driver.back()
        logger.info("back operation")

    # 校验方法----------------------------------------------------------------------------------------------------------

    # 验证元素包含文本
    def element_should_contain(self, locator, expected, message=''):
        logger.info("Verifying element '%s' contains text '%s'." %
                    (locator, expected))
        actual = self._get_text(locator)
        if not message:
            message = "Element '%s' should have contained text '%s' but its text was '%s'." % (
                locator, expected, actual)
        self._test_case.assertIn(expected, actual, message)

    # 验证元素不包含文本
    def element_should_not_contain(self, locator, expected, message=''):
        logger.info("Verifying element '%s' does not contain text '%s'." %
                    (locator, expected))
        actual = self._get_text(locator)
        if not message:
            message = "Element '%s' should not contain text '%s' but it did." % (
                locator, expected)
        self._test_case.assertNotIn(expected, actual, message)

    # 验证元素的文本
    def element_text_should_be(self, locator, expected, message=''):
        logger.info("Verifying element '%s' contains exactly text '%s'." %
                    (locator, expected))
        actual = self._get_text(locator)
        message = "The text of element '%s' should have been '%s' but in fact it was '%s'." % (
            locator, expected, actual)
        self._test_case.assertEqual(expected, actual, message)

    # 验证元素的属性值
    def element_attribute_should_be(self,
                                    locator,
                                    attribute_name,
                                    expected,
                                    tag=None,
                                    message=''):
        logger.info(
            "Verifying element '%s' contains exactly attribute text '%s'." %
            (locator, expected))
        actual = self._get_element_attribute(locator, attribute_name, tag)
        message = "The attribute text of element '%s' should have been '%s' but in fact it was '%s'." % (
            locator, expected, actual)
        self._test_case.assertEqual(expected, actual, message)

    # 验证页面包含某元素
    def page_should_contain_element(self, locator, tag=None, message=''):
        if not self._is_element_present(locator, tag):
            if not message:
                message = "Page should have contained element '%s' but did not" % locator
            raise AssertionError(message)
        logger.info("Current page contains element '%s'." % locator)

    # 验证页面不包含某元素
    def page_should_not_contain_element(self, locator, tag=None, message=''):
        if self._is_element_present(locator, tag):
            if not message:
                message = "Page should not have contained element '%s'" % locator
            raise AssertionError(message)
        logger.info("Current page does not contain element '%s'." % locator)

    # 点击方法----------------------------------------------------------------------------------------------------------

    # 点击元素
    def click_element(self, locator: object) -> object:
        logger.info("Clicking element '%s'." % locator)
        self._element_find(locator, True, True).click()

    # 点击按钮
    def click_button(self, locator):
        logger.info("Clicking button '%s'." % locator)
        element = self._element_find(locator, True, False, 'input')
        if element is None:
            element = self._element_find(locator, True, True, 'button')
        element.click()

    # 文本输入方法------------------------------------------------------------------------------------------------------

    # 文本框输入
    def input_text(self, locator, text):
        logger.info("Typing text '%s' into text field '%s'" % (text, locator))
        element = self._element_find(locator, True, True)
        element.clear()
        element.send_keys(text)

    def focus(self, locator):
        element = self._element_find(locator, True, True)
        ActionChains(self.driver).move_to_element(element).perform()

    # 显式等待方法------------------------------------------------------------------------------------------------------
    # 等待元素加载
    def wait_until_page_contains_element(
            self,
            locator: object,
            tag: object = None,
            error: object = None,
            timeout: object = config.TIMEOUT) -> object:
        if not error:
            error = "Element '%s' did not appear in '%s's." % (locator,
                                                               timeout)
        try:
            WebDriverWait(self.driver, timeout).until(
                lambda x: self._element_finder.find(x, locator, tag=tag))
            logger.info("Wait page contains element '%s'." % locator)
        except TimeoutException:
            raise AssertionError(error)

    # 等待元素消失
    def wait_until_page_does_not_contains_element(self,
                                                  locator,
                                                  tag=None,
                                                  error=None,
                                                  timeout=config.TIMEOUT):
        if not error:
            error = "Element '%s' did not disappear in %s" % (locator, timeout)
        try:
            WebDriverWait(self.driver, timeout).until_not(
                lambda x: self._element_finder.find(x, locator, tag=tag))
            logger.info("Wait page does not contains element '%s'" % locator)
        except TimeoutException:
            raise AssertionError(error)

    # 截图方法并保存到screenshots目录下
    def take_screenshot(self, current_file_path):
        screen_path = os.path.join(
            config.SCREENSHOTS_PATH,
            os.path.basename((os.path.split(current_file_path)[0])))
        if not os.path.exists(screen_path):
            os.makedirs(screen_path)
        i = 1
        screen_name = os.path.basename(
            os.path.splitext(os.path.realpath(current_file_path))
            [0]) + "_" + str(i) + '.png'
        while os.path.exists(os.path.join(screen_path, screen_name)):
            i = i + 1
            screen_name = os.path.basename(
                os.path.splitext(os.path.realpath(current_file_path))
                [0]) + "_" + str(i) + '.png'
        try:
            self.driver.get_screenshot_as_file(
                os.path.join(screen_path, screen_name))
            logger.info("save screenshot name: '%s'" % screen_name)
        except Exception as e:
            logger.error(e)
コード例 #28
0
    else:
        return max(1 + height(t.left), 1 + height(t.right))


def check_balance(t):
    tc.assertLess(abs(height(t.left) - height(t.right)), 2,
                  'Tree is out of balance')


t = AVLTree()
vals = list(range(1000))
random.shuffle(vals)
for i in range(len(vals)):
    t.add(vals[i])
    for x in vals[:i + 1]:
        tc.assertIn(x, t, 'Element added not in tree')
    traverse(t.root, check_balance)

random.shuffle(vals)
for i in range(len(vals)):
    del t[vals[i]]
    for x in vals[i + 1:]:
        tc.assertIn(x, t, 'Incorrect element removed from tree')
    for x in vals[:i + 1]:
        tc.assertNotIn(x, t, 'Element removed still in tree')
    traverse(t.root, check_balance)

# In[ ]:

# In[ ]:
コード例 #29
0
 def test_charge_monstres(self):
     monstres = self.game.charge_monstres()
     TestCase.assertIn(self, monstres[0], self.game.monster_layer)
コード例 #30
0
# response = requests.get("https://www.zhihu.com", headers=headers)
# # print(response.apparent_encoding)
# response.encoding = response.apparent_encoding
# print(response.text)

addr = r"C:\Users\Administrator\Desktop\test\requests.xlsx"
wb = load_workbook(addr)
ws = wb[wb.sheetnames[0]]

row_max = ws.max_row
con_max = ws.max_column
for j in ws.rows:
    # print("开始使用浏览器:{} 发送请求 {}".format(j[0].value, j[1].value), end="\t")
    print("开始使用浏览器:{} 发送请求".format(j[0].value), end="\t")
    headers = {"User-Agent": j[1].value}
    response = requests.get("https://www.zhihu.com", headers=headers)
    # 获取自身编码格式,用于解码
    response.encoding = response.apparent_encoding
    http_test = response.text
    try:
        try:
            TestCase.assertIn(TestCase(), "知乎 - 有问题上知乎", http_test)
            print("成功登陆-断言成功!")
        except:
            TestCase.assertIn(TestCase(), "你正在使用的浏览器版本过低,将不能正常浏览和使用知乎。",
                              http_test)
            print("提醒更新-断言成功!")
    except:
        print("断言失败!")
wb.save(addr)
コード例 #31
0
    def assertIn(self, member, container, msg=None):
        if hasattr(TestCase, 'assertIn'):
            return TestCase.assertIn(self, member, container, msg)

        return self.assertTrue(member in container)
コード例 #32
0
ファイル: __init__.py プロジェクト: kiik/flask-security
    def assertIn(self, member, container, msg=None):
        if hasattr(TestCase, 'assertIn'):
            return TestCase.assertIn(self, member, container, msg)

        return self.assertTrue(member in container)
コード例 #33
0
def should_contains(test: unittest.TestCase, except_value, real_value):
    return test.assertIn(except_value, real_value)
コード例 #34
0
def assert_has_parameters(tester: TestCase, instrument: Instrument,
                          parameters: List[str]):

    for p in parameters:
        tester.assertIn(p, instrument.parameters)
コード例 #35
0
 def test_knleess(self):
     g3 = graph_mani.knlee(self.g1)
     TestCase.assertEqual(self, g3.start_node.get_next_node(master_key=True)[0], self.g1.start_node)
     TestCase.assertIn(self, g3.end_node, self.g1.end_node.get_next_node(master_key=True))
コード例 #36
0
ファイル: basepage.py プロジェクト: sharly2012/uiautomation
class BasePage(metaclass=ABCMeta):
    def __init__(self, driver):
        """
        :param driver:打开浏览器驱动
        """
        self.driver: WebDriver = driver
        self.accept_next_alert = True
        self.case = TestCase()
        self.path = root_path
        self.page_confirm()

    @abstractmethod
    def page_confirm(self):
        raise NotImplementedError('请实现确认是否是当前页面的逻辑')

    def open_url(self, url):
        """
        打开URL
        :param url: url
        :return: None
        """
        logger.info("浏览器打开链接: {}".format(url))
        self.driver.get(url)

    def get_title(self):
        """
        获取当前页面的title
        :return: title
        """
        logger.info("当前页面的title为: %s" % self.driver.title)
        return self.driver.title

    @fail_screenshot
    def find_element(self, *locator):
        """
        根据locator查找页面元素
        :param locator: tuple(find_by, value)
        :return: WebElement
        """
        try:
            WebDriverWait(self.driver, 10,
                          0.5).until(EC.visibility_of_element_located(locator))
            element = self.driver.find_element(*locator)
            return element
        except NoSuchElementException:
            logger.error('Can not find the element: %s' % locator[1])
            raise
        except TimeoutException:
            logger.error('Can not find element: %s in 10 seconds' % locator[1])
            raise

    @fail_screenshot
    def find_elements(self, *locator):
        """
        根据locator查找页面上的所有元素
        :param locator: tuple(find_by, value)
        :return: WebElements
        """
        try:
            elements = WebDriverWait(
                self.driver, 10,
                0.5).until(lambda driver: driver.find_elements(*locator))
            return elements
        except NoSuchElementException:
            logger.error('Can not find the element: %s' % locator[1])
            raise
        except TimeoutException:
            logger.error('Can not find the element: %s in 10 seconds' %
                         locator[1])
            raise

    def get_screen_img(self):
        """
        截图且保存在screenshots目录下
        :return:
        """
        now = time.strftime("%Y-%m-%d_%H_%M_%S")
        file_name = now + '.png'
        screen_path = os.path.join(self.path, 'screenshots', file_name)
        try:
            self.driver.get_screenshot_as_file(screen_path)
            allure.attach.file(screen_path,
                               attachment_type=allure.attachment_type.PNG)
            logger.info("页面已截图,截图保存的路径为: %s" % screen_path)
        except ScreenshotException as e:
            logger.error("截图失败 %s" % e)

    @fail_screenshot
    def click(self, locator):
        """
        根据locator点击元素
        :param locator:
        :return:
        """
        logger.info('Click element by %s: %s ......' %
                    (locator[0], locator[1]))
        try:
            element = self.find_element(*locator)
            element.click()
        except ElementNotVisibleException as e:
            logger.error("无法点击元素: %s" % e)
            raise

    @fail_screenshot
    def clear(self, locator):
        """输入文本框清空操作"""
        logger.info('Clear the input %s: %s ......' % (locator[0], locator[1]))
        try:
            element = self.find_element(*locator)
            element.clear()
            logger.info('清空文本框 ......')
        except Exception as e:
            logger.error("Failed to clear in input box with %s" % e)
            raise

    @fail_screenshot
    def send_keys(self, locator, text):
        """
        文本框输入内容
        :param locator:
        :param text:
        :return:
        """
        logger.info('Input element by %s: %s, value: %s ......' %
                    (locator[0], locator[1], text))
        try:
            element = self.find_element(*locator)
            element.send_keys(text)
        except Exception as e:
            logger.error("Failed to type in input box with %s" % e)
            raise

    @fail_screenshot
    def move_to_element(self, locator):
        """
        鼠标悬停操作
        Usage:
        element = ("id","xxx")
        driver.move_to_element(element)
        """
        logger.info('Move the mouse to the locator %s: %s' %
                    (locator[0], locator[1]))
        try:
            element = self.find_element(*locator)
            ActionChains(self.driver).move_to_element(element).perform()
        except Exception as e:
            logger.error(
                'Move the mouse to the locator appear error {}'.format(e))
            raise

    @fail_screenshot
    def drag_loc_from_to(self, source, target):
        """
        At source WebElement hold the left mouse drag to the target WebElement then release
        :param source:
        :param target:
        :return:
        """
        logger.info('Click the %s and then move to $s' % (source, target))
        try:
            ele_source = self.find_element(*source)
            ele_target = self.find_element(*target)
            ActionChains(self.driver).drag_and_drop(ele_source,
                                                    ele_target).perform()
        except Exception as e:
            logger.error('Click the and then move element error: {}'.format(e))
            raise

    def back(self):
        """
        浏览器返回窗口
        """
        logger.info('返回上一个页面')
        self.driver.back()

    def forward(self):
        """
        浏览器前进下一个窗口
        """
        logger.info('前进到下一个页面')
        self.driver.forward()

    @staticmethod
    def sleep(seconds=2):
        time.sleep(seconds)
        logger.info("等待 %d 秒" % seconds)

    def close(self):
        """
        关闭浏览器
        """
        try:
            self.driver.close()
            logger.info('关闭浏览器窗口')
        except Exception as e:
            logger.error("关闭浏览器窗口失败 %s" % e)

    def quit(self):
        """
        退出浏览器
        """
        self.driver.quit()

    def get_current_url(self):
        """获取当前页面的url"""
        return self.driver.current_url

    @fail_screenshot
    def get_text(self, locator):
        """获取文本"""
        try:
            element = self.find_element(*locator)
            return element.text
        except AttributeError as e:
            logger.error(e)
            self.get_screen_img()
            raise

    @fail_screenshot
    def get_attribute(self, locator, attribute_name):
        """获取属性"""
        try:
            element = self.find_element(*locator)
            return element.get_attribute(attribute_name)
        except AttributeError as e:
            logger.error(e)
            self.get_screen_img()
            raise

    def js_execute(self, js):
        """执行js"""
        try:
            self.driver.execute_script(js)
        except JavascriptException as e:
            logger.error('Execute js error: {}'.format(e))

    @fail_screenshot
    def js_focus_element(self, locator):
        """聚焦元素"""
        try:
            target = self.find_element(*locator)
            self.driver.execute_script("arguments[0].scrollIntoView(true);",
                                       target)
        except Exception as e:
            logger.error('Focus element error: {}'.format(e))

    def js_scroll_top(self):
        """滚动到顶部"""
        js = "window.scrollTo(0,0)"
        self.driver.execute_script(js)

    def js_scroll_end(self):
        """滚动到底部(只能滚动body的滚动条)"""
        js = "window.scrollTo(0,document.body.scrollHeight)"
        self.driver.execute_script(js)

    @fail_screenshot
    def select_by_index(self, locator, index):
        """通过索引,index是索引第几个,从0开始"""
        try:
            element = self.find_element(*locator)
            Select(element).select_by_index(index)
        except Exception as e:
            logger.info(e)
            self.get_screen_img()
            raise

    @fail_screenshot
    def select_by_value(self, locator, value):
        """下拉框通过value属性选择"""
        try:
            element = self.find_element(*locator)
            Select(element).select_by_value(value)
        except Exception as e:
            logger.info(e)
            self.get_screen_img()
            raise e

    @fail_screenshot
    def select_by_text(self, locator, choice_text):
        """下拉框通过文本值定位"""
        try:
            element = self.find_element(*locator)
            Select(element).select_by_value(choice_text)
        except Exception as e:
            logger.error(e)
            self.get_screen_img()
            raise

    @fail_screenshot
    def is_text_in_element(self, locator, text, timeout=10):
        """判断文本在元素里,没定位到元素返回False,定位到元素返回判断结果布尔值"""
        try:
            result = WebDriverWait(self.driver, timeout, 1).until(
                EC.text_to_be_present_in_element(locator, text))
            return result
        except TimeoutException:
            logger.info("元素没有定位到:" + str(locator))
            return False

    @fail_screenshot
    def is_text_in_value(self, locator, value, timeout=10):
        """
        判断元素的value值,没定位到元素返回false,定位到返回判断结果布尔值
        result = driver.text_in_element(element, text)
        """
        try:
            result = WebDriverWait(self.driver, timeout, 0.5).until(
                EC.text_to_be_present_in_element_value(locator, value))
            return result
        except TimeoutException:
            logger.info("元素没定位到:" + str(locator))
            return False

    @fail_screenshot
    def is_title(self, title, timeout=10):
        """判断title完全等于"""
        result = WebDriverWait(self.driver, timeout,
                               0.5).until(EC.title_is(title))
        return result

    @fail_screenshot
    def is_title_contains(self, title, timeout=10):
        """判断title包含"""
        result = WebDriverWait(self.driver, timeout,
                               0.5).until(EC.title_contains(title))
        return result

    @fail_screenshot
    def is_selected(self, locator, timeout=10):
        """判断元素被选中,返回布尔值"""
        result = WebDriverWait(self.driver, timeout, 0.5).until(
            EC.element_located_to_be_selected(locator))
        return result

    @fail_screenshot
    def is_selected_be(self, locator, selected=True, timeout=10):
        """判断元素的状态,selected是期望的参数true/False
        返回布尔值"""
        result = WebDriverWait(self.driver, timeout, 0.5).until(
            EC.element_located_selection_state_to_be(locator, selected))
        return result

    def is_alert_present(self, timeout=10):
        """判断页面是否有alert,
        有返回alert(注意这里是返回alert,不是True)
        没有返回False"""
        result = WebDriverWait(self.driver, timeout,
                               0.5).until(EC.alert_is_present())
        return result

    def alert_accept(self):
        """接受alert"""
        try:
            alert = self.driver.switch_to.window()
            logger.info('alert test is %s' % alert.text)
            alert.accept()
        except UnexpectedAlertPresentException as e:
            logger.error('Alert accept error: {}'.format(e))
        except NoAlertPresentException as e1:
            logger.error('Alert accept error: {}'.format(e1))

    @fail_screenshot
    def is_visibility(self, locator, timeout=10):
        """元素可见返回本身,不可见返回False"""
        try:
            result = WebDriverWait(self.driver, timeout, 0.5).until(
                EC.visibility_of_element_located(locator))
            return result
        except TimeoutException as e:
            logger.info(e)
            return False

    @fail_screenshot
    def is_invisibility(self, locator, timeout=10):
        """元素可见返回False,不可见返回True,没找到元素也返回True"""
        result = WebDriverWait(self.driver, timeout, 0.5).until(
            EC.invisibility_of_element_located(locator))
        return result

    def is_clickable(self, locator, timeout=10):
        """元素可以点击is_enabled返回元素本身,不可点击返回False"""
        result = WebDriverWait(self.driver, timeout,
                               0.5).until(EC.element_to_be_clickable(locator))
        return result

    def is_located(self, locator, timeout=10):
        """判断元素有没被定位到(并不意味着可见),定位到返回element,没定位到返回False"""
        result = WebDriverWait(self.driver, timeout, 0.5).until(
            EC.presence_of_element_located(locator))
        return result

    def set_element_wait(self, wait_time, locator):
        WebDriverWait(self.driver, wait_time,
                      0.5).until(EC.presence_of_element_located(locator))

    def upload_file(self, locator, file_path):
        """input 上传文件"""
        try:
            self.find_element(*locator).send_keys(file_path)
            self.sleep(2)
        except Exception as e:
            logger.error("Failed to upload file %s" % e)
            self.get_screen_img()

    def switch_handle(self, title_name):
        """根据窗口title切换窗口"""
        all_handles = self.driver.window_handles()
        for handle in all_handles:
            if self.driver.title.find(title_name) == -1:
                self.driver.switch_to_window(handle)
            else:
                print("Can't find the handle")

    def is_element_present(self, how, what):
        try:
            self.driver.find_element(by=how, value=what)
            return True
        except NoSuchElementException as e:
            logger.error("Element is not present. %s" % e)
            return False

    def close_alert_and_get_its_text(self):
        """close the alter and return its text"""
        try:
            alert = self.driver.switch_to.alert()
            alert_text = alert.text
            logger.info('Close the alert %s ......' % alert_text)
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally:
            self.accept_next_alert = True

    def get_attribute_text(self, locator):
        try:
            text_content = self.find_element(
                *locator).get_attribute('textContent')
        except Exception as e:
            logger.error("Failed to upload file %s" % e)
            text_content = ''
            self.get_screen_img()
        return text_content

    def get_screenshot(self, case_name):
        """screen shot"""
        file_name = case_name
        file_path = os.path.join(root_path, 'screenshots', file_name + '.png')
        self.driver.get_screenshot_as_file(file_path)
        allure.attach.file(file_path,
                           attachment_type=allure.attachment_type.PNG)
        logger.info("Screen shot had been saved: %s" % file_path)
        return file_path

    @staticmethod
    def get_current_time():
        temp = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
        return temp

    @staticmethod
    def get_current_data():
        return time.strftime("%Y-%m-%d", time.localtime())

    def verify_true(self, expr, msg=None):
        try:
            self.case.assertTrue(expr, msg)
        except Exception as e:
            self.get_screen_img()
            raise e

    def verify_in(self, member, container, msg=None):
        try:
            self.case.assertIn(member, container, msg)
        except Exception as e:
            self.get_screen_img()
            raise e