Best Python code snippet using behave
test_step_parsing.py
Source:test_step_parsing.py  
...32    and this is line four,33    with spaces at the beginning34  """35'''.strip()36def parse_steps(step):37    """Parse a step, prefixing it with a feature and a scenario header."""38    feature = """39    Feature: parse a step40    Scenario: parse a single step41    """42    feature += step43    return Feature.from_string(feature).scenarios[0].steps44def first_line_of(step):45    """46    Return the first line of a step47    """48    return step.strip().splitlines()[0]49def test_step_has_repr():50    """51    Step implements __repr__ nicely52    """53    step, = parse_steps(I_HAVE_TASTY_BEVERAGES)54    assert_equal(55        repr(step),56        '<Step: "' + first_line_of(I_HAVE_TASTY_BEVERAGES) + '">'57    )58def test_can_get_sentence_from_string():59    """60    It should extract the sentence string from the whole step61    """62    step, = parse_steps(I_HAVE_TASTY_BEVERAGES)63    assert isinstance(step, Step)64    assert_equal(65        step.sentence,66        first_line_of(I_HAVE_TASTY_BEVERAGES)67    )68def test_can_parse_keys_from_table():69    """70    It should take the keys from the step, if it has a table71    """72    step, = parse_steps(I_HAVE_TASTY_BEVERAGES)73    assert_equal(step.keys, ('Name', 'Type', 'Price'))74def test_can_parse_tables():75    """76    It should have a list of data from a given step, if it has a table77    """78    step, = parse_steps(I_HAVE_TASTY_BEVERAGES)79    assert_equal(step.hashes, (80        {81            'Name': 'Skol',82            'Type': 'Beer',83            'Price': '3.80'84        },85        {86            'Name': 'Nestea',87            'Type': 'Ice-tea',88            'Price': '2.10'89        },90    ))91def test_can_parse_a_unary_array_from_single_step():92    """93    It should extract a single ordinary step correctly into an array of steps94    """95    steps = parse_steps(I_HAVE_TASTY_BEVERAGES)96    assert_equal(len(steps), 1)97    assert isinstance(steps[0], Step)98    assert_equal(steps[0].sentence,99                 first_line_of(I_HAVE_TASTY_BEVERAGES))100def test_can_parse_a_unary_array_from_complicated_step():101    """102    It should extract a single tabular step correctly into an array of steps103    """104    steps = parse_steps(I_LIKE_VEGETABLES)105    assert_equal(len(steps), 1)106    assert isinstance(steps[0], Step)107    assert_equal(steps[0].sentence, first_line_of(I_LIKE_VEGETABLES))108def test_can_parse_regular_step_followed_by_tabular_step():109    """110    It should correctly extract two steps (one regular, one tabular) into an111    array.112    """113    steps = parse_steps(I_LIKE_VEGETABLES + I_HAVE_TASTY_BEVERAGES)114    assert_equal(len(steps), 2)115    assert isinstance(steps[0], Step)116    assert isinstance(steps[1], Step)117    assert_equal(steps[0].sentence, first_line_of(I_LIKE_VEGETABLES))118    assert_equal(steps[1].sentence, first_line_of(I_HAVE_TASTY_BEVERAGES))119def test_can_parse_tabular_step_followed_by_regular_step():120    """"121    It should correctly extract two steps (one tabular, one regular) into122    an array.123    """124    steps = parse_steps(I_HAVE_TASTY_BEVERAGES + I_LIKE_VEGETABLES)125    assert_equal(len(steps), 2)126    assert isinstance(steps[0], Step)127    assert isinstance(steps[1], Step)128    assert_equal(steps[0].sentence, first_line_of(I_HAVE_TASTY_BEVERAGES))129    assert_equal(steps[1].sentence, first_line_of(I_LIKE_VEGETABLES))130def test_can_parse_two_ordinary_steps():131    """132    It should correctly extract two ordinary steps into an array.133    """134    steps = parse_steps(I_DIE_HAPPY + I_LIKE_VEGETABLES)135    assert_equal(len(steps), 2)136    assert isinstance(steps[0], Step)137    assert isinstance(steps[1], Step)138    assert_equal(steps[0].sentence, first_line_of(I_DIE_HAPPY))139    assert_equal(steps[1].sentence, first_line_of(I_LIKE_VEGETABLES))140def test_multiline_is_part_of_previous_step():141    """142    It should correctly parse a multi-line string as part of the preceding step143    """144    steps = parse_steps(MULTI_LINE)145    assert_equal(len(steps), 1)146    assert isinstance(steps[0], Step)147    assert_equal(steps[0].sentence, 'Given I have a string like so:')148def test_table_escaping():149    """150    Table columns can be correctly escaped151    """152    steps = parse_steps(r"""153    Given I have items in my table:154        | Column 1                 |155        | This is a column         |156        | This is \| also a column |157        | This is \\ a backslash   |158    """)159    assert_equal(len(steps), 1)160    step, = steps161    assert_equal(step.table, (162        (r'Column 1',),163        (r'This is a column',),164        (r'This is | also a column',),165        (r'This is \ a backslash',),166    ))167def test_multiline_is_parsed():168    """Test parsing a multiline string in a step."""169    step, = parse_steps(MULTI_LINE)170    assert_equal(step.sentence, 'Given I have a string like so:')171    assert_equal(step.multiline, u"""This is line one172and this is line two173and this is line three174  and this is line four,175  with spaces at the beginning""")176def test_step_with_hash():177    """Test parsing a step with a hash"""178    step, = parse_steps('''179    Given I have product #1234 in my cart180    ''')181    assert_equal(step.sentence, 'Given I have product #1234 in my cart')182def test_comments():183    """Test parsing Gherkin comments."""184    steps = parse_steps('''185    # A comment186    Given I have a comment187                        # Another comment188    And I have another comment189    ''')190    assert_equal(191        [step.sentence for step in steps],192        [193            'Given I have a comment',194            'And I have another comment',195        ]196    )197def test_multiline_with_hash():198    """Test parsing a multiline with a hash"""199    step, = parse_steps('''200    Given I have the following products in my cart:201    """202    #1234203    #2345204    """205    ''')...test_formatter.py
Source:test_formatter.py  
...55def test_formatter_parses_each_step_from_flyer(successfulFlyer):56    successfulFlyer.create_sequence()57    successfulFlyer.run_sequence()58    formatter = Formatter()59    results = formatter.parse_steps(successfulFlyer)60    assert len(results) == 561def test_get_student_out_finds_main_out_if_no_postprocess():62    env = Environment(falconf_string="""63    test:64        main: python testMain.py65    """)66    flyer = Flyer(mode='test', env=env)67    flyer.create_sequence()68    flyer.run_sequence()69    formatter = Formatter(flyer)70    steps = formatter.parse_steps(flyer)71    assert 'student_outtttt' in formatter.get_student_out(flyer)72def test_get_student_out_finds_postprocess_out_if_postprocess():73    env = Environment(falconf_string="""74    test:75        main: python testMain.py76        postprocess: echo 'possssst'77    """)78    flyer = Flyer(mode='test', env=env)79    flyer.create_sequence()80    flyer.run_sequence()81    formatter = Formatter(flyer)82    steps = formatter.parse_steps(flyer)83    assert 'possssst' in formatter.get_student_out(flyer)84def test_get_student_out_finds_udacity_out_if_no_postprocess():85    env = Environment(falconf_string="""86    test:87        main: python testMain.py88    """)89    msg = 'this is a message'90    flyer = Flyer(mode='test', env=env)91    flyer.create_sequence()92    flyer.run_sequence()93    formatter = Formatter(flyer)94    steps = formatter.parse_steps(flyer)95    write_udacity_out(msg)96    assert msg in formatter.get_student_out(flyer)97def test_get_is_correct_is_none_if_no_tag():98    env = Environment(falconf_string="""99    test:100        main: python testMain.py101    """)102    flyer = Flyer(mode='test', env=env)103    flyer.create_sequence()104    flyer.run_sequence()105    formatter = Formatter(flyer)106    steps = formatter.parse_steps(flyer)107    student_out = formatter.get_student_out(flyer)108    assert formatter.get_is_correct(student_out) is None109def test_get_is_correct_is_false_if_fail_tag():110    # manually passes in output111    env = Environment(falconf_string="""112    test:113        main: echo '<::FAIL>'114    """)115    flyer = Flyer(mode='test', env=env)116    flyer.create_sequence()117    flyer.run_sequence()118    formatter = Formatter(flyer)119    steps = formatter.parse_steps(flyer)120    student_out = formatter.get_student_out(flyer)121    assert not formatter.get_is_correct(student_out)122def test_get_is_correct_is_true_if_pass_tag():123    # output pulled from udacity_out file124    msg = '<::PASS>'125    write_udacity_out(msg)126    formatter = Formatter()...main.py
Source:main.py  
...21    if steps is None:22        print("Unsolvable!")23    else:24        print("\nSolution:")25        print(parse_steps(steps))26        print("Solution is valid." if verify_steps(27            starting_numbers, target, steps) else "Solution is invalid!")28def get_steps(remaining_numbers, target, current=None, steps=None, closest=None):29    if current is None:30        steps = []31    for operand_pair in itertools.permutations(remaining_numbers, 2):32        (operand1, operand2) = operand_pair33        for operation in ['+', '-', '*', '/']:34            if operation == '/' and (operand2 == 0 or not is_integer_result(operand1, operand2)):35                continue36            elif operation == '-' and operand2 > operand1:37                continue38            current = operate(operand1, operand2, operation)39            offby = abs(current - target)40            if current == 0 or len(str(abs(current))) > 4:41                continue42            steps.append([operand1, operation, operand2, current])43            if offby < 10:44                print(f"Off by {offby}:")45                print(parse_steps(steps))46            # print(f'{operand1} {operation} {operand2} = {current}')47            if current == target:48                return steps49            remaining_numbers_copy = remaining_numbers.copy()50            remaining_numbers_copy.remove(operand1)51            remaining_numbers_copy.remove(operand2)52            remaining_numbers_copy.append(current)53            new_steps = get_steps(remaining_numbers_copy,54                                  target, current, steps, closest)55            if new_steps is None:56                steps.pop()57            else:58                return steps59def generate_starting_numbers():60    starting_numbers = []61    big_count = 062    for i in range(6):63        if random.randint(0, 1) and not big_count >= 4:64            starting_numbers.append(random.choice(BIG_NUMBERS))65            big_count += 166        else:67            starting_numbers.append(random.randint(1, 10))68    return starting_numbers69def operate(operand1, operand2, operation):70    if operation == '+':71        return operand1 + operand272    if operation == '-':73        return operand1 - operand274    if operation == '*':75        return operand1 * operand276    if operation == '/':77        if not is_integer_result(operand1, operand2):78            raise Exception(79                f"Result of {operand1} / {operand2} is not an integer")80        return operand1 // operand281def is_integer_result(operand1, operand2):82    return (operand1 / operand2).is_integer()83def verify_steps(starting_numbers, target, steps):84    result: int85    for step in steps:86        (operand1, operation, operand2, r) = step87        if r != operate(operand1, operand2, operation):88            return False89        try:90            starting_numbers.append(r)91            starting_numbers.remove(operand1)92            starting_numbers.remove(operand2)93        except ValueError:94            return False95        result = r96    if result != target:97        return False98    return True99def parse_steps(steps):100    final_string = ""101    for step in steps:102        final_string += f"{step[0]} {step[1]} {step[2]} = {step[3]}\n"103    return final_string104if __name__ == '__main__':...enot.py
Source:enot.py  
...36        self._override_conf = config.get('override', False)37        self._disable_prebuild = config.get('disable_prebuild', False)38        self._fullname = config.get('fullname', None)39        self._compare_versions = config.get('compare_versions', True)40        self._prebuild = EnotConfig.parse_steps(config.get('prebuild', []))41        self._install = EnotConfig.parse_steps(config.get('install', []))42        self._is_release = False43        for action in self.install:44            if isinstance(action, Release):45                self._is_release = True46        self._uninstall = EnotConfig.parse_steps(config.get('uninstall', []))47    @property48    def is_release(self) -> bool:49        return self._is_release50    @classmethod51    def from_path(cls, path: str, url=None) -> 'EnotConfig':52        content = read_file(join(path, 'enot_config.json'))53        name = path.split('/')[-1:]  # use project dir name as a name if not set in config54        return cls(json.loads(content), url=url, name=name)55    @classmethod56    def from_package(cls, package: TarFile, url: str, config: ConfigFile) -> 'EnotConfig':57        f = package.extractfile('enot_config.json')58        content = f.read()59        conf = cls(json.loads(content.decode('utf-8')), url=url)60        if config is not None:61            if config.fullname:  # overwrite fullname by package's fullname (from dep.config).62                conf.fullname = config.fullname63        return conf64    def need_enotify(self):65        return False66    def get_compiler(self):67        return Compiler.ENOT68    def __parse_build_vars(self, parsed):69        self._build_vars = parsed.get('build_vars', [])70        self._c_build_vars = parsed.get('c_build_vars', [])71    @staticmethod72    def parse_steps(steps: list) -> list:73        actions = []74        for step in steps:75            [(action_type, params)] = step.items()76            actions.append(action_factory.get_action(action_type, params))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
