Best Python code snippet using pytest-bdd_python
__main__.py
Source:__main__.py  
1# Copyright 2016-2020, Pulumi Corporation.  All rights reserved.2import pulumi3from pulumi_policy import (4    EnforcementLevel,5    PolicyConfigSchema,6    PolicyPack,7    ResourceValidationPolicy,8    StackValidationPolicy,9)10schema = None11initial_config = None12verify = None13test_scenario = pulumi.Config().require_int("scenario")14if test_scenario == 1:15    # Test scenario 1: String from config.16    schema = PolicyConfigSchema(17        properties={18            "foo": {"type": "string"},19        },20    )21    def check(config):22        assert config["foo"] == "bar"23    verify = check24elif test_scenario == 2:25    # Test scenario 2: Default string value specified in schema used.26    schema = PolicyConfigSchema(27        properties={28            "foo": {29                "type": "string",30                "default": "bar",31            },32        },33    )34    def check(config):35        assert config["foo"] == "bar"36    verify = check37elif test_scenario == 3:38    # Test scenario 3: Default number value specified in schema used.39    schema = PolicyConfigSchema(40        properties={41            "foo": {42                "type": "number",43                "default": 42,44            },45        },46    )47    def check(config):48        assert config["foo"] == 4249    verify = check50elif test_scenario == 4:51    # Test scenario 4: Specified config value overrides default value.52    schema = PolicyConfigSchema(53        properties={54            "foo": {55                "type": "string",56                "default": "bar",57            },58        },59    )60    def check(config):61        assert config["foo"] == "overridden"62    verify = check63elif test_scenario == 5:64    # Test scenario 5: Default value specified in schema for required field used.65    schema = PolicyConfigSchema(66        properties={67            "foo": {68                "type": "string",69                "default": "bar",70            },71        },72        required=["foo"],73    )74    def check(config):75        assert config["foo"] == "bar"76    verify = check77elif test_scenario == 6:78    # Test scenario 6: Required config property not set.79    schema = PolicyConfigSchema(80        properties={81            "foo": {82                "type": "string",83            },84        },85        required=["foo"],86    )87elif test_scenario == 7:88    # Test scenario 7: Default value set to incorrect type.89    schema = PolicyConfigSchema(90        properties={91            "foo": {92                "type": "string",93                "default": 1,94            },95        },96    )97elif test_scenario == 8:98    # Test scenario 8: Default value too long.99    schema = PolicyConfigSchema(100        properties={101            "foo": {102                "type": "string",103                "maxLength": 3,104                "default": "this value is too long",105            },106        },107    )108elif test_scenario == 9:109    # Test scenario 9: Default value too short.110    schema = PolicyConfigSchema(111        properties={112            "foo": {113                "type": "string",114                "minLength": 50,115                "default": "this value is too short",116            },117        },118    )119elif test_scenario == 10:120    # Test scenario 10: Default value set to invalid enum value.121    schema = PolicyConfigSchema(122        properties={123            "foo": {124                "type": "string",125                "enum": ["bar", "baz"],126                "default": "blah",127            },128        },129    )130elif test_scenario == 11:131    # Test scenario 11: Default value set to invalid constant value.132    schema = PolicyConfigSchema(133        properties={134            "foo": {135                "const": "bar",136                "default": "blah",137            },138        },139    )140elif test_scenario == 12:141    # Test scenario 12: Incorrect type.142    schema = PolicyConfigSchema(143        properties={144            "foo": {145                "type": "string",146            },147        },148    )149elif test_scenario == 13:150    # Test scenario 13: Invalid enum value.151    schema = PolicyConfigSchema(152        properties={153            "foo": {154                "enum": ["bar", "baz"],155            },156        },157    )158elif test_scenario == 14:159    # Test scenario 14: Invalid constant value.160    schema = PolicyConfigSchema(161        properties={162            "foo": {163                "const": "bar",164            },165        },166    )167elif test_scenario == 15:168    # Test scenario 15: Invalid constant value.169    schema = PolicyConfigSchema(170        properties={171            "foo": {172                "type": "string",173                "maxLength": 3,174            },175            "bar": {176                "type": "integer",177            },178        },179    )180elif test_scenario == 16:181    # Test scenario 16: Number (int) from config.182    schema = PolicyConfigSchema(183        properties={184            "foo": {185                "type": "number",186            },187        },188    )189    def check(config):190        assert config["foo"] == 42191    verify = check192elif test_scenario == 17:193    # Test scenario 17: Number (float) from config.194    schema = PolicyConfigSchema(195        properties={196            "foo": {197                "type": "number",198            },199        },200    )201    def check(config):202        assert config["foo"] == 3.14203    verify = check204elif test_scenario == 18:205    # Test scenario 18: Integer from config.206    schema = PolicyConfigSchema(207        properties={208            "foo": {209                "type": "integer",210            },211        },212    )213    def check(config):214        assert config["foo"] == 42215    verify = check216elif test_scenario == 19:217    # Test scenario 19: Boolean (true) from config.218    schema = PolicyConfigSchema(219        properties={220            "foo": {221                "type": "boolean",222            },223        },224    )225    def check(config):226        assert config["foo"] == True227    verify = check228elif test_scenario == 20:229    # Test scenario 20: Boolean (false) from config.230    schema = PolicyConfigSchema(231        properties={232            "foo": {233                "type": "boolean",234            },235        },236    )237    def check(config):238        assert config["foo"] == False239    verify = check240elif test_scenario == 21:241    # Test scenario 21: Object from config.242    schema = PolicyConfigSchema(243        properties={244            "foo": {245                "type": "object",246            },247        },248    )249    def check(config):250        assert isinstance(config["foo"], dict)251        assert config["foo"]["bar"] == "baz"252    verify = check253elif test_scenario == 22:254    # Test scenario 22: Array from config.255    schema = PolicyConfigSchema(256        properties={257            "foo": {258                "type": "array",259            },260        },261    )262    def check(config):263        assert isinstance(config["foo"], list)264        assert len(config["foo"]) == 3265        assert config["foo"][0] == "a"266        assert config["foo"][1] == "b"267        assert config["foo"][2] == "c"268    verify = check269elif test_scenario == 23:270    # Test scenario 23: Null from config.271    schema = PolicyConfigSchema(272        properties={273            "foo": {274                "type": "null",275            },276        },277    )278    def check(config):279        assert config["foo"] is None280    verify = check281elif test_scenario == 24:282    # Test scenario 24: Initial config.283    schema = PolicyConfigSchema(284        properties={285            "foo": {286                "type": "string",287            },288        },289    )290    initial_config = {291        "resource-validation": {292            "foo": "hello world",293        },294        "stack-validation": {295            "foo": "hello world",296        },297    }298    def check(config):299        assert config["foo"] == "hello world"300    verify = check301elif test_scenario == 25:302    # Test scenario 25: Initial config overridden.303    schema = PolicyConfigSchema(304        properties={305            "foo": {306                "type": "string",307            },308        },309    )310    initial_config = {311        "resource-validation": {312            "foo": "hello world",313        },314        "stack-validation": {315            "foo": "hello world",316        },317    }318    def check(config):319        assert config["foo"] == "overridden"320    verify = check321else:322    raise AssertionError(f"Unexpected test_scenario {test_scenario}.")323def validate(args, report_violation):324    if verify is not None:325        verify(args.get_config())326PolicyPack(327    name="config-policy",328    enforcement_level=EnforcementLevel.MANDATORY,329    policies=[330        ResourceValidationPolicy(331            name="resource-validation",332            description="Verifies policy config during resource validation.",333            validate=validate,334            config_schema=schema,335        ),336        StackValidationPolicy(337            name="stack-validation",338            description="Verifies policy config during stack validation.",339            validate=validate,340            config_schema=schema,341        ),342    ],343    initial_config=initial_config,...test_with_test_spec.py
Source:test_with_test_spec.py  
1import unittest2from inspect import getmodule, currentframe3from unittest_specs import expect4from unittest_specs.with_test_spec import scenario, setup, run, teardown, assertion5class TestWithScenarioDSL(unittest.TestCase):6    def setUp(self) -> None:7        def increment():8            self.test_value += 19        self.test_value = 010        self.increment = increment11    def tearDown(self) -> None:12        module = getmodule(currentframe())13        if "TestSuite" in module.__dict__:14            if "test_scenario" in module.__dict__["TestSuite"].__dict__:15                module.__dict__["TestSuite"] = type("TestSuite", (unittest.TestCase,), {})16    def test_with_statement_registers_class_in_module(self):17        with scenario("test scenario"):18            pass19        module = getmodule(currentframe())20        self.assertEqual(module.__dict__["TestSuite"].__name__, "TestSuite")21    def test_with_statement_registers_scenario_function_in_class(self):22        with scenario("test scenario"):23            pass24        module = getmodule(currentframe())25        self.assertEqual(module.__dict__["TestSuite"].__dict__["test_scenario"].__name__, "test_scenario")26    def test_with_statement_registers_two_scenario_function_in_class(self):27        with scenario("first test scenario"):28            pass29        with scenario("second test scenario"):30            pass31        module = getmodule(currentframe())32        self.assertEqual(module.__dict__["TestSuite"].__dict__["test_first_test_scenario"].__name__, "test_first_test_scenario")33        self.assertEqual(module.__dict__["TestSuite"].__dict__["test_second_test_scenario"].__name__, "test_second_test_scenario")34    def test_execution_throws_exception_when_no_run_action_is_defined(self):35        with scenario("test scenario"):36            pass37        module = getmodule(currentframe())38        test_run = module.__dict__["TestSuite"].__dict__["test_scenario"]39        self.assertRaises(Exception, test_run)40    def test_setup_adds_setup_action_to_test_execution(self):41        with scenario("test scenario") as test_scenario:42            test_scenario @ setup << self.increment43            test_scenario @ run << (lambda: print(""))44        module = getmodule(currentframe())45        module.__dict__["TestSuite"].__dict__["test_scenario"]()46        self.assertEqual(1, self.test_value)47    def test_setup_adds_two_setup_actions_to_test_execution(self):48        with scenario("test scenario") as test_scenario:49            test_scenario @ setup << self.increment50            test_scenario @ setup << self.increment51            test_scenario @ run << (lambda: print(""))52        module = getmodule(currentframe())53        module.__dict__["TestSuite"].__dict__["test_scenario"]()54        self.assertEqual(2, self.test_value)55    def test_run_sets_test_execution_action(self):56        with scenario("test scenario") as test_scenario:57            test_scenario @ run << self.increment58        module = getmodule(currentframe())59        module.__dict__["TestSuite"].__dict__["test_scenario"]()60        self.assertEqual(1, self.test_value)61    def test_setting_a_second_run_action_throws_an_exception(self):62        def create_scenario():63            with scenario("test scenario") as test_scenario:64                test_scenario @ run << self.increment65                test_scenario @ run << self.increment66        self.assertRaises(Exception, create_scenario)67    def test_teardown_adds_teardown_action_to_test_execution(self):68        with scenario("test scenario") as test_scenario:69            test_scenario @ run << (lambda: print(""))70            test_scenario @ teardown << self.increment71        module = getmodule(currentframe())72        module.__dict__["TestSuite"].__dict__["test_scenario"]()73        self.assertEqual(1, self.test_value)74    def test_teardown_adds_two_teardown_actions_to_test_execution(self):75        with scenario("test scenario") as test_scenario:76            test_scenario @ run << (lambda: print(""))77            test_scenario @ teardown << self.increment78            test_scenario @ teardown << self.increment79        module = getmodule(currentframe())80        module.__dict__["TestSuite"].__dict__["test_scenario"]()81        self.assertEqual(2, self.test_value)82with scenario("free standing scenario") as standalone_test_scenario:83    class Adder:84        def __init__(self):85            self.__result = 086        def perform_addition(self, a, b):87            self.__result = a + b88        def reset_result(self):89            self.__result = 090        @property91        def result(self):92            return self.__result93    adder = Adder()94    standalone_test_scenario @ setup << (lambda: adder.reset_result())95    standalone_test_scenario @ run << (lambda: adder.perform_addition(1, 4))96    standalone_test_scenario @ assertion << expect(lambda: adder.result).to_be(5)...get_all_corrections.py
Source:get_all_corrections.py  
1#!/usr/bin/env python32import subprocess3import json4import sys5import os6def CopyAndAdapt(test_scenario):7  # Move the old corrections to a stored file8  correction_file =  "scripts/srtr/brass/results/{}_corrections.txt".format(test_scenario)9  command = "mv scripts/srtr/brass/results/correction_trace.txt {}".format(correction_file)10  result = subprocess.call(command, shell=True)11  # Get the adaptation from SRTR12  command = "./bin/srtr_brass {}".format(correction_file)13  result = subprocess.call(command, shell=True)14  command = "mv brass_srtr.json scripts/srtr/brass/results/adaptations/{}_adaptation.json".format(test_scenario)15  result = subprocess.call(command, shell=True)16  command = "mv brass_srtr_starved.json scripts/srtr/brass/results/adaptations/{}_starved_adaptation.json".format(test_scenario)17  result = subprocess.call(command, shell=True)18directory_path = "scripts/srtr/brass/results/"19nominal_path = directory_path + "nominal_traces/"20degraded_path = directory_path + "degraded_traces/"21test_scenario = ""22for file in sorted(os.listdir(nominal_path)):23  filename = os.fsdecode(file)24  nominal_file = nominal_path + filename25  degraded_file = degraded_path + filename26  first_underscore = filename.find("_")27  current_scenario = filename[:first_underscore]28  # Identify if we've changed test scenarios or not29  if (current_scenario != test_scenario and test_scenario != ""):30    print("Adapting")31    CopyAndAdapt(test_scenario)32  test_scenario = current_scenario33  # Run the correction generation34  if (os.path.isfile(nominal_file) and os.path.isfile(degraded_file)):35    command = "./bin/gen_corrections {} {}".format(nominal_file,36                                                   degraded_file)37    result = subprocess.call(command, shell=True)38# Finish the last test scenario...tests.py
Source:tests.py  
1from django.test import TestCase2# Create your tests here.3from game.models import Scenario, Input4import random5n_scenarios = 106test_scenarios = []7class gameTest(TestCase):8    fixtures = ['test_data.xml']9    def test_index(self):10        print("testing index...")11        resp=self.client.get('/game')12        self.assertEqual(resp.status_code, 200)13    def test_game(self):14        print("t6esting game...")15        resp=self.client.get('/game/play')16        self.assertEqual(resp.status_code, 200)17        print("SKIPPED TESTING GAME")18    #tests the creation of several scenarios, from input variables for the scenario fields19    def test_create(self):20        for i in range(0, n_scenarios):21            test_scenario = {"text": "Test Scenario "+str(i), "scenario_id": i, "order_n": 0}22            test_scenarios.append(test_scenario)23        for test_scenario in test_scenarios:24            Scenario.objects.create(text = test_scenario["text"], scenario_id= test_scenario["scenario_id"], order_n= test_scenario["order_n"] )25        self.assertEqual(len(test_scenarios), Scenario.objects.all().count())26        self.assertEqual(len(test_scenarios), n_scenarios)...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!!
