Best Python code snippet using lisa_python
testutils.py
Source:testutils.py
...131 LeafSettings.CACHE_FOLDER.value = None132 LeafSettings.USER_PKG_FOLDER.value = None133 # Clean volatile folder134 rmtree_force(self.volatile_folder)135 def _get_default_variables(self):136 out = OrderedDict()137 out["{TESTS_LEAF_VERSION}"] = __version__138 out["{TESTS_PLATFORM_SYSTEM}"] = platform.system()139 out["{TESTS_PLATFORM_MACHINE}"] = platform.machine()140 out["{TESTS_PLATFORM_RELEASE}"] = platform.release()141 out["{LEAF_PROJECT_ROOT_FOLDER}"] = LEAF_PROJECT_ROOT_FOLDER142 out["{TESTS_FOLDER}"] = self.test_folder143 return out144 def assertFileContentEquals(self, actual_file: Path, template_name: str, variables: dict = None): # noqa: N802145 content_variables = self._get_default_variables()146 if variables is not None:147 content_variables.update(variables)148 check_content(self, self.get_template_file(template_name), get_lines(actual_file), content_variables)149 def get_template_file(self, template_name):150 # Template is a file name151 self.assertTrue(isinstance(template_name, str))152 class_folder = TEST_RESOURCES_FOLDER / "expected_ouput" / self.__class__.__name__153 template = self.id().split(".")[-1] + "_" + template_name154 return class_folder / template155 def assertStdout(self, template_out=None, template_err=None, variables: dict = None): # noqa: N802156 """157 Possibles values for templates :158 - None -> the stream is not checked159 - Empty list, tuple or set -> the stream is checked as empty160 - File name -> the stream is compared to the file content161 """162 content_variables = self._get_default_variables()163 if variables is not None:164 content_variables.update(variables)165 return ContentChecker(166 self,167 expected_out=self.get_template_file(template_out) if template_out else None,168 expected_err=self.get_template_file(template_err) if template_err else None,169 variables=content_variables,170 )171class LeafTestCaseWithRepo(LeafTestCase):172 @classmethod173 def setUpClass(cls):174 LeafTestCase.setUpClass()175 generate_repository(TEST_REMOTE_PACKAGE_SOURCE, LeafTestCaseWithRepo._TEST_FOLDER / "repository")176 @property177 def repository_folder(self):178 out = self.test_folder / "repository"179 out.mkdir(parents=True, exist_ok=True)180 return out181 @property182 def remote_url1(self):183 return (self.repository_folder / "index.json").as_uri()184 @property185 def remote_url2(self):186 return str(self.repository_folder / "index2.json")187 def _get_default_variables(self):188 out = super()._get_default_variables()189 out["{TESTS_REMOTE_URL}"] = self.remote_url1190 out["{TESTS_REMOTE_URL2}"] = self.remote_url2191 return out192 def check_content(self, content, pislist):193 self.assertEqual(len(content), len(pislist))194 for pis in pislist:195 self.assertTrue(PackageIdentifier.parse(pis) in content)196 def check_installed_packages(self, pislist, install_folder=None):197 if install_folder is None:198 install_folder = self.install_folder199 for pis in pislist:200 folder = install_folder / str(pis)201 self.assertTrue(folder.is_dir(), msg=str(folder))202 count = 0...
test_variable.py
Source:test_variable.py
...11 secret.reset()12 def test_in_env(self) -> None:13 os.environ["LISA_normal_value"] = "value_from_env"14 os.environ["S_LISA_normal_entry"] = "s_value_from_env"15 variables = self._get_default_variables()16 variables.update(variable._load_from_env())17 data = self._replace_and_validate(variables, {"normal_entry": "******"})18 self.assertEqual("value_from_env", data["nested"]["normal_value"])19 self.assertEqual("s_value_from_env", data["normal_entry"])20 def test_in_pair(self) -> None:21 pair1 = "normal_value:nv_from_pair"22 pair2 = "S:normal_entry:s_value_from_env"23 variables = self._get_default_variables()24 variables.update(variable.add_secrets_from_pairs([pair1, pair2]))25 data = self._replace_and_validate(variables, {"normal_entry": "******"})26 self.assertEqual("nv_from_pair", data["nested"]["normal_value"])27 self.assertEqual("s_value_from_env", data["normal_entry"])28 def test_in_normal_file_outside_secret(self) -> None:29 self._test_files(30 "variable_normal.yml",31 True,32 {33 "normal_value": "******",34 "normal_entry": "******",35 "secret_guid": "12345678-****-****-****-********90ab",36 "secret_int": "1****0",37 "secret_head_tail": "a****h",38 },39 )40 def test_in_normal_file(self) -> None:41 self._test_files(42 "variable_normal.yml",43 False,44 {45 "secret_guid": "12345678-****-****-****-********90ab",46 "secret_int": "1****0",47 "secret_head_tail": "a****h",48 },49 )50 def test_in_secret_file_outside_secret(self) -> None:51 self._test_files(52 "variable_secret.yml",53 True,54 {55 "normal_value": "******",56 "normal_entry": "******",57 "secret_guid": "12345678-****-****-****-********90ab",58 "secret_int": "1****0",59 "secret_head_tail": "a****h",60 },61 )62 def test_in_secret_file(self) -> None:63 self._test_files(64 "variable_secret.yml",65 False,66 {},67 )68 def test_in_runbook_format_file(self) -> None:69 runbook_data: Dict[str, Any] = {"variable": [{"file": "variable_normal.yml"}]}70 data = self._test_runbook_file_entry(71 runbook_data,72 {73 "secret_guid": "12345678-****-****-****-********90ab",74 "secret_int": "1****0",75 "secret_head_tail": "a****h",76 },77 {},78 )79 self.assertEqual("12345678-abcd-efab-cdef-1234567890ab", data["list"][0])80 self.assertEqual(1234567890, data["list"][1]["dictInList"])81 self.assertEqual("abcdefgh", data["headtail"])82 self.assertEqual("normal_value", data["nested"]["normal_value"])83 self.assertEqual("entry_value", data["normal_entry"])84 def test_in_variable_path_with_variable(self) -> None:85 runbook_data: Dict[str, Any] = {86 "variable": [87 {"file": "variable_$(var_in_var1).yml"},88 {"name": "var_in_var1", "value": "$(var_in_var2)"},89 {"name": "var_in_var2", "value": "normal"},90 ]91 }92 data = self._test_runbook_file_entry(93 runbook_data,94 {95 "secret_guid": "12345678-****-****-****-********90ab",96 "secret_int": "1****0",97 "secret_head_tail": "a****h",98 },99 {},100 )101 self.assertEqual("12345678-abcd-efab-cdef-1234567890ab", data["list"][0])102 self.assertEqual(1234567890, data["list"][1]["dictInList"])103 self.assertEqual("abcdefgh", data["headtail"])104 self.assertEqual("normal_value", data["nested"]["normal_value"])105 self.assertEqual("entry_value", data["normal_entry"])106 def test_in_runbook_path_with_variable(self) -> None:107 runbook_data: Dict[str, Any] = {108 "variable": [{"file": "variable_$(var_in_cmd).yml"}]109 }110 data = self._test_runbook_file_entry(111 runbook_data,112 {113 "secret_guid": "12345678-****-****-****-********90ab",114 "secret_int": "1****0",115 "secret_head_tail": "a****h",116 },117 {118 "var_in_cmd": variable.VariableEntry(119 name="var_in_cmd", data="normal", is_used=False120 )121 },122 )123 self.assertEqual("12345678-abcd-efab-cdef-1234567890ab", data["list"][0])124 self.assertEqual(1234567890, data["list"][1]["dictInList"])125 self.assertEqual("abcdefgh", data["headtail"])126 self.assertEqual("normal_value", data["nested"]["normal_value"])127 self.assertEqual("entry_value", data["normal_entry"])128 def test_in_runbook_format_variable(self) -> None:129 runbook_data: Dict[str, Any] = {130 "variable": [131 {"name": "normal_value", "value": "normal_value"},132 {"name": "normal_entry", "value": "entry_value"},133 {134 "name": "secret_guid",135 "value": "12345678-abcd-efab-cdef-1234567890ab",136 "is_secret": True,137 "mask": "guid",138 },139 {140 "name": "secret_int",141 "value": 1234567890,142 "is_secret": True,143 "mask": "headtail",144 },145 {146 "name": "secret_head_tail",147 "value": "abcdefgh",148 "is_secret": True,149 "mask": "headtail",150 },151 ]152 }153 data = self._test_runbook_file_entry(154 runbook_data,155 {156 "secret_guid": "12345678-****-****-****-********90ab",157 "secret_int": "1****0",158 "secret_head_tail": "a****h",159 },160 {},161 )162 self.assertEqual("12345678-abcd-efab-cdef-1234567890ab", data["list"][0])163 self.assertEqual(1234567890, data["list"][1]["dictInList"])164 self.assertEqual("abcdefgh", data["headtail"])165 self.assertEqual("normal_value", data["nested"]["normal_value"])166 self.assertEqual("entry_value", data["normal_entry"])167 def test_in_runbook_ordered(self) -> None:168 runbook_data: Dict[str, Any] = {169 "variable": [170 {"file": "variable_normal.yml"},171 {"name": "normal_value", "value": "normal_value1"},172 {"name": "normal_entry", "value": "entry_value1"},173 {174 "name": "secret_guid",175 "value": "12345678-abcd-efab-cdef-1234567890ac",176 "is_secret": True,177 "mask": "guid",178 },179 {180 "name": "secret_int",181 "value": 1234567891,182 "is_secret": True,183 "mask": "headtail",184 },185 {186 "name": "secret_head_tail",187 "value": "abcdefgi",188 "is_secret": True,189 "mask": "headtail",190 },191 ]192 }193 data = self._test_runbook_file_entry(194 runbook_data,195 {196 "secret_guid": "12345678-****-****-****-********90ac",197 "secret_int": "1****1",198 "secret_head_tail": "a****i",199 },200 {},201 )202 self.assertEqual("12345678-abcd-efab-cdef-1234567890ac", data["list"][0])203 self.assertEqual(1234567891, data["list"][1]["dictInList"])204 self.assertEqual("abcdefgi", data["headtail"])205 self.assertEqual("normal_value1", data["nested"]["normal_value"])206 self.assertEqual("entry_value1", data["normal_entry"])207 def test_variable_not_found(self) -> None:208 variables = self._get_default_variables()209 with self.assertRaises(LisaException) as cm:210 variable.replace_variables({"item": "$(notexists)"}, variables)211 self.assertIsInstance(cm.exception, LisaException)212 self.assertIn("cannot find variable", str(cm.exception))213 def test_variable_not_used(self) -> None:214 variables = self._get_default_variables()215 variables["unused"] = variable.VariableEntry(name="unused", data="value")216 self.assertFalse(variables["unused"].is_used)217 self.assertFalse(variables["normal_value"].is_used)218 self._replace_and_validate(variables, {"normal_entry": "original"})219 self.assertFalse(variables["unused"].is_used)220 self.assertTrue(variables["normal_value"].is_used)221 def test_invalid_file_extension(self) -> None:222 variables = self._get_default_variables()223 with self.assertRaises(LisaException) as cm:224 variables.update(variable._load_from_file("file.xml"))225 self.assertIsInstance(cm.exception, LisaException)226 self.assertIn("variable support only yaml and yml", str(cm.exception))227 def _test_runbook_file_entry(228 self,229 data: Any,230 secret_variables: Dict[str, str],231 current_variables: Dict[str, variable.VariableEntry],232 ) -> Any:233 constants.RUNBOOK_PATH = Path(__file__).parent234 variables = self._get_default_variables()235 variables.update(variable._load_from_runbook(data, current_variables))236 data = self._replace_and_validate(variables, secret_variables)237 return data238 def _test_files(239 self, file_name: str, all_secret: bool, secret_variables: Dict[str, str]240 ) -> Any:241 constants.RUNBOOK_PATH = Path(__file__).parent242 variables = self._get_default_variables()243 variables.update(variable._load_from_file(file_name, is_secret=all_secret))244 data = self._replace_and_validate(variables, secret_variables)245 self.assertEqual("normal_value", data["nested"]["normal_value"])246 self.assertEqual("entry_value", data["normal_entry"])247 self.assertEqual("12345678-abcd-efab-cdef-1234567890ab", data["list"][0])248 self.assertEqual(1234567890, data["list"][1]["dictInList"])249 self.assertEqual("abcdefgh", data["headtail"])250 return data251 def _verify_secret(252 self, variables: Dict[str, variable.VariableEntry], secrets: Dict[str, str]253 ) -> None:254 log = get_logger()255 copied_variables = dict(variables)256 for secret_name, expected_value in secrets.items():257 secret_name = secret_name.lower()258 value = copied_variables[secret_name].data259 del copied_variables[secret_name]260 with self.assertLogs("lisa") as cm:261 log.info(f"MUST_SECRET[{value}]")262 self.assertListEqual(263 [f"INFO:lisa.:MUST_SECRET[{expected_value}]"],264 cm.output,265 f"key: {secret_name}, value: {value}, "266 f"expected: {expected_value} should be secret",267 )268 for key, unsecured_value in copied_variables.items():269 with self.assertLogs("lisa") as cm:270 log.info(f"MUST_NOT_SECRET[{unsecured_value}]")271 self.assertListEqual(272 [f"INFO:lisa.:MUST_NOT_SECRET[{unsecured_value}]"],273 cm.output,274 f"key: {key}, value: {unsecured_value} shouldn't be secret",275 )276 def _get_default_variables(self) -> Dict[str, variable.VariableEntry]:277 data = {278 "normal_value": variable.VariableEntry("normal_value", "original"),279 "normal_entry": variable.VariableEntry("normal_entry", "original"),280 "secret_guid": variable.VariableEntry("secret_guid", "original"),281 "secret_int": variable.VariableEntry("secret_int", "original"),282 "secret_head_tail": variable.VariableEntry("secret_head_tail", "original"),283 }284 return data285 def _replace_and_validate(286 self, variables: Dict[str, variable.VariableEntry], secrets: Dict[str, str]287 ) -> Dict[str, Any]:288 data = variable.replace_variables(self._get_default_data(), variables=variables)289 assert isinstance(data, dict), f"actual: {type(data)}"290 self.assertDictEqual(...
docker.py
Source:docker.py
...40 return self._build_file41 @build_file.setter42 def build_file(self, value):43 self._build_file = value44 def _get_default_variables(self):45 return dict(46 DOCKER=which("docker"),47 USE_BUILDX="",48 DOCKER_BUILD="$(if $(USE_BUILDX),$(DOCKER) buildx build,$(DOCKER) image build)",49 DOCKER_BUILD_OPTIONS="--build-arg IMAGE=$(DOCKER_IMAGE) --build-arg TAG=$(DOCKER_TAG)",50 DOCKER_BUILD_MORE_OPTIONS="",51 DOCKER_PUSH="$(DOCKER) image push",52 DOCKER_PUSH_OPTIONS="",53 DOCKER_RUN="$(DOCKER) run",54 DOCKER_RUN_COMMAND="",55 DOCKER_RUN_NAME="$(PACKAGE)_run",56 DOCKER_RUN_OPTIONS="",57 DOCKER_RUN_PORTS="",58 )59 def _get_default_image_variables(self):60 return dict(61 DOCKER_BUILD_FILE="", # will be set at runtime.62 DOCKER_IMAGE="", # will be set at runtime, see #71.63 DOCKER_TAG="$(VERSION)",64 )65 def disable_builder(self):66 self.builder = None67 self._variables = []68 self.scripts = Namespace()69 def use_default_builder(self):70 self.builder = DOCKER71 self._variables = [self._get_default_variables(), self._get_default_image_variables()]72 self.scripts = Namespace(73 build=Script(74 "$(DOCKER_BUILD) -f $(DOCKER_BUILD_FILE) $(DOCKER_BUILD_OPTIONS) $(DOCKER_BUILD_MORE_OPTIONS) -t $(DOCKER_IMAGE):$(DOCKER_TAG) .",75 doc="Build a docker image.",76 ),77 push=Script(78 "$(DOCKER_PUSH) $(DOCKER_PUSH_OPTIONS) $(DOCKER_IMAGE):$(DOCKER_TAG)",79 doc="Push docker image to remote registry.",80 ),81 run=Script(82 "$(DOCKER_RUN) $(DOCKER_RUN_OPTIONS) --interactive $(shell test -t 0 && echo '--tty') --rm --name=$(DOCKER_RUN_NAME) $(DOCKER_RUN_PORTS) $(DOCKER_IMAGE):$(DOCKER_TAG) $(DOCKER_RUN_COMMAND)",83 doc="Run the default entry point in a container based on our docker image.",84 ),85 shell=Script(86 'DOCKER_RUN_COMMAND="/bin/bash" $(MAKE) docker-run',87 doc="Run bash in a container based on our docker image.",88 ),89 )90 def use_rocker_builder(self):91 self.use_default_builder()92 self.builder = ROCKER93 self._variables = [94 self._get_default_variables(),95 self._get_default_image_variables(),96 dict(97 ROCKER=which("rocker"),98 ROCKER_BUILD="$(ROCKER) build",99 ROCKER_BUILD_OPTIONS="",100 ROCKER_BUILD_VARIABLES="--var DOCKER_IMAGE=$(DOCKER_IMAGE) --var DOCKER_TAG=$(DOCKER_TAG) --var PYTHON_REQUIREMENTS_FILE=requirements-prod.txt",101 ),102 ]103 self.scripts.build.set("$(ROCKER_BUILD) $(ROCKER_BUILD_OPTIONS) $(ROCKER_BUILD_VARIABLES) .")104 self.scripts.push.set('ROCKER_BUILD_OPTIONS="$(ROCKER_BUILD_OPTIONS) --push" $(MAKE) docker-build')105 @property106 def variables(self):107 for variables in self._variables:108 yield from variables.items()...
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!!