How to use mock_config method in Pytest

Best Python code snippet using pytest

commands.py

Source:commands.py Github

copy

Full Screen

...26 fake_supplier_pricelist_item,27 fake_warehouse_stock_item,28 fake_web_menu_item,29 random_string)30def get_mock_config():31 return {32 "paths": {33 "database": ":memory:",34 "imports": {35 "web_menu_mappings": "path/import/web_menu_mappings",36 "pricelist": "path/import/pricelist",37 "supplier_pricelist": "path/import/supplier_pricelist",38 "missing_images_report": "path/import/missing_images_report",39 },40 "exports": {41 "contract_item_task": "path/export/contract_item_task",42 "gtin_report": "path/export/gtin_report",43 "images_dir": "path/export/images_dir",44 "pricelist": "path/export/pricelist",45 "price_changes_report": "path/export/price_changes_report",46 "product_price_task": "path/export/product_price_task",47 "supplier_pricelist": "path/export/supplier_pricelist_{supp_code}",48 "supplier_price_changes_report": "path/export/supplier_price_changes_report",49 "tickets_list": "path/export/tickets_list",50 "web_product_menu_data": "path/export/web_product_menu_data",51 "web_data_updates_report": "path/export/web_data_updates_report",52 "missing_images_report": "path/export/missing_images_report",53 },54 "remote": {55 "pricelist": "path/remote/pricelist",56 "supplier_pricelist": "path/remote/supplier_pricelist",57 "supplier_pricelist_import": "path/remote/supplier_pricelist_import",58 }59 },60 "ssh": {61 "hostname": "pronto.example.com",62 "username": "prontousername",63 "password": "prontopassword",64 },65 "price_rules": {66 "ignore": [67 "NA",68 ]69 },70 "bin_locations": {71 "ignore": [72 "IGNORED",73 ]74 },75 "gtin": {76 "ignore_brands": [77 "IGN",78 ]79 }80 }81class CommandTests(DatabaseTestCase):82 def test_commands_generator(self):83 """84 Generates a list of command classes.85 """86 expected_commands = [87 Commands.download_spl,88 Commands.fetch_images,89 Commands.generate_spl,90 Commands.help,91 Commands.missing_gtin,92 Commands.price_calc,93 Commands.upload_pricelist,94 Commands.upload_spls,95 Commands.web_update,96 ]97 self.assertEqual(98 list(commands()),99 expected_commands)100 def test_get_command(self):101 """102 Gets a command given its class name or one of its aliases.103 """104 fixtures = [105 ("download_spl", Commands.download_spl),106 ("download-spl", Commands.download_spl),107 ("dspl", Commands.download_spl),108 ("help", Commands.help),109 ("h", Commands.help),110 ("missing_gtin", Commands.missing_gtin),111 ("missing-gtin", Commands.missing_gtin),112 ("mg", Commands.missing_gtin),113 ("mgtin", Commands.missing_gtin),114 ("price_calc", Commands.price_calc),115 ("price-calc", Commands.price_calc),116 ("pc", Commands.price_calc),117 ("upload_pricelist", Commands.upload_pricelist),118 ("upload-pricelist", Commands.upload_pricelist),119 ("upl", Commands.upload_pricelist),120 ("upload_spls", Commands.upload_spls),121 ("upload-spls", Commands.upload_spls),122 ("uspls", Commands.upload_spls),123 ("generate_spl", Commands.generate_spl),124 ("generate-spl", Commands.generate_spl),125 ("gspl", Commands.generate_spl),126 ("web_update", Commands.web_update),127 ("web-update", Commands.web_update),128 ("wu", Commands.web_update),129 ("wupd", Commands.web_update),130 ("fetch_images", Commands.fetch_images),131 ("fetch-images", Commands.fetch_images),132 ("fi", Commands.fetch_images),133 ("fimg", Commands.fetch_images),134 ]135 for command_name, expected_command in fixtures:136 self.assertEqual(expected_command, get_command(command_name))137 @patch("sys.stdout", new_callable=io.StringIO)138 def test_command_help(self, mock_stdout):139 """140 Prints a list of commands.141 """142 mock_config = get_mock_config()143 Commands.help(mock_config)()144 printed_lines = mock_stdout.getvalue().split("\n")145 self.assertEqual(printed_lines[1], "Available commands:")146 for index, command in enumerate(commands()):147 line = printed_lines[index + 3]148 self.assertIn(command.__name__, line)149 self.assertIn(command.__doc__.strip(), line)150 @patch("pxi.commands.get_scp_client")151 def test_command_download_spl_ssh(self, mock_get_scp_client):152 """153 download_spl command downloads supplier pricelist usingn SCP.154 """155 mock_config = get_mock_config()156 mock_scp_client = MagicMock()157 mock_get_scp_client.return_value = mock_scp_client158 Commands.download_spl(mock_config)()159 mock_get_scp_client.assert_called_with(*mock_config["ssh"].values())160 mock_scp_client.get.assert_called_with(161 mock_config["paths"]["remote"]["supplier_pricelist"],162 mock_config["paths"]["imports"]["supplier_pricelist"])163 @patch("requests.get")164 def test_command_download_spl_https(self, mock_requests_get):165 """166 download_spl command downloads supplier pricelist usingn HTTPS.167 """168 mock_config = get_mock_config()169 mock_config["paths"]["remote"]["supplier_pricelist"] = (170 "https://path/remote/supplier_pricelist")171 with patch("builtins.open", mock_open()) as get_mock_file:172 Commands.download_spl(mock_config)()173 mock_file = get_mock_file()174 mock_requests_get.assert_called_with(175 mock_config["paths"]["remote"]["supplier_pricelist"])176 mock_file.write.assert_called_with(177 mock_requests_get.return_value.content)178 @patch("os.listdir")179 @patch("os.path")180 @patch("pxi.commands.get_scp_client")181 def test_command_upload_spls(182 self,183 mock_get_scp_client,184 mock_os_path,185 mock_os_listdir):186 """187 upload_spls command uploads supplier pricelists usingn SCP.188 """189 mock_config = get_mock_config()190 filename = "supplier_pricelist_{supp_code}.csv"191 export_path = f"export/path/{filename}"192 remote_path = f"remote/path/{filename}"193 mock_config["paths"]["exports"]["supplier_pricelist"] = export_path194 mock_config["paths"]["remote"]["supplier_pricelist_import"] = remote_path195 supp_code = random_string(3)196 mock_os_path.dirname.return_value = "export/path"197 mock_os_path.basename.return_value = filename198 mock_os_listdir.return_value = [199 filename.format(supp_code=supp_code),200 random_string(20),201 ]202 mock_scp_client = MagicMock()203 mock_get_scp_client.return_value = mock_scp_client204 Commands.upload_spls(mock_config)()205 mock_os_path.dirname.assert_called_with(export_path)206 mock_os_listdir.assert_called_with(mock_os_path.dirname.return_value)207 mock_get_scp_client.assert_called_with(*mock_config["ssh"].values())208 mock_scp_client.put.assert_called_with(209 export_path.format(supp_code=supp_code),210 remote_path.format(supp_code=supp_code))211 @patch("pxi.commands.get_scp_client")212 def test_command_upload_pricelist(self, mock_get_scp_client):213 """214 download_spl command uploads pricelist usingn SCP.215 """216 mock_config = get_mock_config()217 mock_scp_client = MagicMock()218 mock_get_scp_client.return_value = mock_scp_client219 Commands.upload_pricelist(mock_config)()220 mock_get_scp_client.assert_called_with(*mock_config["ssh"].values())221 mock_scp_client.put.assert_called_with(222 mock_config["paths"]["exports"]["pricelist"],223 mock_config["paths"]["remote"]["pricelist"])224 @patch("pxi.commands.export_tickets_list")225 @patch("pxi.commands.export_contract_item_task")226 @patch("pxi.commands.export_product_price_task")227 @patch("pxi.commands.export_pricelist")228 @patch("pxi.commands.export_price_changes_report")229 @patch("pxi.commands.recalculate_contract_prices")230 @patch("pxi.commands.recalculate_sell_prices")231 @patch("pxi.commands.import_data")232 def test_command_price_calc(233 self,234 mock_import_data,235 mock_recalculate_sell_prices,236 mock_recalculate_contract_prices,237 mock_export_price_changes_report,238 mock_export_pricelist,239 mock_export_product_price_task,240 mock_export_contract_item_task,241 mock_export_tickets_list):242 """243 price_calc command imports data, calculates prices, exports 244 reports/data.245 """246 mock_config = get_mock_config()247 import_paths = mock_config["paths"]["imports"]248 export_paths = mock_config["paths"]["exports"]249 inv_item = fake_inventory_item()250 con_item = fake_contract_item(inv_item)251 ws_item = fake_warehouse_stock_item(inv_item)252 price_rule = fake_price_rule()253 pr_item = fake_price_region_item(inv_item, price_rule, {254 "code": "",255 })256 price_change = fake_sell_price_change(pr_item)257 mock_recalculate_sell_prices.return_value = [price_change]258 mock_recalculate_contract_prices.return_value = [con_item]259 self.seed([260 inv_item,261 con_item,262 ws_item,263 price_rule,264 pr_item,265 ])266 command = Commands.price_calc(mock_config)267 command.db_session = self.db_session268 command()269 mock_import_data.assert_called_with(command.db_session, import_paths, [270 InventoryItem,271 WarehouseStockItem,272 PriceRule,273 PriceRegionItem,274 ContractItem,275 ], force_imports=False)276 mock_recalculate_sell_prices.assert_called_with(277 [pr_item], command.db_session)278 mock_recalculate_contract_prices.assert_called_with(279 [price_change], command.db_session)280 mock_export_price_changes_report.assert_called_with(281 export_paths["price_changes_report"],282 [price_change])283 mock_export_pricelist.assert_called_with(284 export_paths["pricelist"],285 [pr_item])286 mock_export_product_price_task.assert_called_with(287 export_paths["product_price_task"],288 [pr_item])289 mock_export_contract_item_task.assert_called_with(290 export_paths["contract_item_task"],291 [con_item])292 mock_export_tickets_list.assert_called_with(293 export_paths["tickets_list"],294 [ws_item])295 @patch("pxi.commands.export_supplier_pricelist")296 @patch("pxi.commands.export_supplier_price_changes_report")297 @patch("pxi.commands.update_supplier_items")298 @patch("pxi.commands.import_supplier_pricelist_items")299 @patch("pxi.commands.import_data")300 def test_command_generate_spl(301 self,302 mock_import_data,303 mock_import_supplier_pricelist_items,304 mock_update_supplier_items,305 mock_export_supplier_price_changes_report,306 mock_export_supplier_pricelist):307 """308 generate_spl command imports data, generates SPL, exports reports/data.309 """310 mock_config = get_mock_config()311 import_paths = mock_config["paths"]["imports"]312 export_paths = mock_config["paths"]["exports"]313 inv_item = fake_inventory_item()314 supp_item = fake_supplier_item(inv_item)315 spl_item = fake_supplier_pricelist_item(supp_item)316 price_change = fake_buy_price_change(supp_item)317 self.seed([318 inv_item,319 supp_item,320 ])321 mock_import_supplier_pricelist_items.return_value = [spl_item]322 mock_update_supplier_items.return_value = [price_change]323 command = Commands.generate_spl(mock_config)324 command.db_session = self.db_session325 command()326 mock_import_data.assert_called_with(command.db_session, import_paths, [327 InventoryItem,328 SupplierItem,329 ], force_imports=False)330 mock_import_supplier_pricelist_items.assert_called_with(331 import_paths["supplier_pricelist"])332 mock_update_supplier_items.assert_called_with(333 [spl_item], command.db_session)334 mock_export_supplier_price_changes_report.assert_called_with(335 export_paths["supplier_price_changes_report"],336 [price_change])337 mock_export_supplier_pricelist.assert_called_with(338 export_paths["supplier_pricelist"].format(339 supp_code=supp_item.code),340 [supp_item])341 @patch("pxi.commands.export_supplier_pricelist")342 @patch("pxi.commands.export_supplier_price_changes_report")343 @patch("pxi.commands.update_supplier_items")344 @patch("pxi.commands.import_supplier_pricelist_items")345 @patch("pxi.commands.import_data")346 def test_command_generate_spl_with_multiple_spl_items_per_inv_item(347 self,348 mock_import_data,349 mock_import_supplier_pricelist_items,350 mock_update_supplier_items,351 mock_export_supplier_price_changes_report,352 mock_export_supplier_pricelist):353 """354 generate_spl command imports data, generates SPL, exports reports/data.355 """356 mock_config = get_mock_config()357 import_paths = mock_config["paths"]["imports"]358 export_paths = mock_config["paths"]["exports"]359 inv_item_1 = fake_inventory_item()360 inv_item_2 = fake_inventory_item()361 supp_item_1a = fake_supplier_item(inv_item_1)362 supp_item_1b = fake_supplier_item(inv_item_1)363 spl_item_1a = fake_supplier_pricelist_item(supp_item_1a)364 spl_item_1b = fake_supplier_pricelist_item(supp_item_1b)365 bp_change_1a = fake_buy_price_change(supp_item_1a)366 bp_change_1b = fake_buy_price_change(supp_item_1b)367 self.seed([368 inv_item_1,369 supp_item_1a,370 supp_item_1b,371 ])372 spl_items = [spl_item_1a, spl_item_1b]373 bp_changes = [bp_change_1a, bp_change_1b]374 mock_import_supplier_pricelist_items.return_value = spl_items375 mock_update_supplier_items.return_value = bp_changes376 command = Commands.generate_spl(mock_config)377 command.db_session = self.db_session378 command()379 mock_import_data.assert_called_with(command.db_session, import_paths, [380 InventoryItem,381 SupplierItem,382 ], force_imports=False)383 mock_import_supplier_pricelist_items.assert_called_with(384 import_paths["supplier_pricelist"])385 mock_update_supplier_items.assert_called_with(386 spl_items, command.db_session)387 mock_export_supplier_price_changes_report.assert_called_with(388 export_paths["supplier_price_changes_report"],389 bp_changes)390 mock_export_supplier_pricelist.assert_has_calls([391 call(392 export_paths["supplier_pricelist"].format(393 supp_code=supp_item_1a.code),394 [supp_item_1a]395 ),396 call(397 export_paths["supplier_pricelist"].format(398 supp_code=supp_item_1b.code),399 [supp_item_1b]400 ),401 ])402 @patch("pxi.commands.export_web_data_updates_report")403 @patch("pxi.commands.export_web_product_menu_data")404 @patch("pxi.commands.update_product_menu")405 @patch("pxi.commands.import_web_menu_item_mappings")406 @patch("pxi.commands.import_data")407 def test_command_web_update(408 self,409 mock_import_data,410 mock_import_web_menu_item_mappings,411 mock_update_product_menu,412 mock_export_web_product_menu_data,413 mock_export_web_data_updates_report):414 """415 web_update command imports data, sorts items into web categories, 416 exports reports and data.417 """418 mock_config = get_mock_config()419 import_paths = mock_config["paths"]["imports"]420 export_paths = mock_config["paths"]["exports"]421 inv_item = fake_inventory_item()422 price_rule = fake_price_rule()423 pr_item = fake_price_region_item(inv_item, price_rule, {424 "code": PriceRegionItem.DEFAULT_REGION_CODE425 })426 web_menu_item = fake_web_menu_item()427 iwd_item = fake_inv_web_data_item(inv_item, None)428 self.seed([429 inv_item,430 price_rule,431 pr_item,432 web_menu_item,433 iwd_item,434 ])435 wmi_mappings = {436 price_rule.code: web_menu_item,437 }438 mock_import_web_menu_item_mappings.return_value = wmi_mappings439 mock_update_product_menu.return_value = [iwd_item]440 command = Commands.web_update(mock_config)441 command.db_session = self.db_session442 command()443 mock_import_data.assert_called_with(command.db_session, import_paths, [444 InventoryItem,445 WebMenuItem,446 PriceRule,447 PriceRegionItem,448 InventoryWebDataItem,449 ], force_imports=False)450 mock_import_web_menu_item_mappings.assert_called_with(451 import_paths["web_menu_mappings"],452 command.db_session)453 mock_update_product_menu.assert_called_with(454 [iwd_item],455 wmi_mappings,456 command.db_session)457 mock_export_web_product_menu_data.assert_called_with(458 export_paths["web_product_menu_data"],459 [iwd_item])460 mock_export_web_data_updates_report.assert_called_with(461 export_paths["web_data_updates_report"],462 [iwd_item])463 @patch("pxi.commands.export_gtin_report")464 @patch("pxi.commands.import_data")465 def test_command_missing_gtin(466 self,467 mock_import_data,468 mock_export_gtin_report):469 """470 missing_gtin command imports data, reports items missing GTIN.471 """472 mock_config = get_mock_config()473 import_paths = mock_config["paths"]["imports"]474 export_paths = mock_config["paths"]["exports"]475 inv_item = fake_inventory_item()476 gtin_item = fake_gtin_item(inv_item, {477 "gtin": "NOT A BARCODE",478 })479 self.seed([480 inv_item,481 gtin_item,482 ])483 command = Commands.missing_gtin(mock_config)484 command.db_session = self.db_session485 command()486 mock_import_data.assert_called_with(command.db_session, import_paths, [487 InventoryItem,488 GTINItem,489 ], force_imports=False)490 mock_export_gtin_report.assert_called_with(491 export_paths["gtin_report"], [inv_item], [])492 @patch("pxi.commands.export_downloaded_images_report")493 @patch("pxi.commands.fetch_images")494 @patch("pxi.commands.import_missing_images_report")495 @patch("pxi.commands.import_data")496 def test_command_fetch_images(497 self,498 mock_import_data,499 mock_import_missing_images_report,500 mock_fetch_images,501 mock_export_downloaded_images_report):502 """503 fetch_images command downloads images, reports on images.504 """505 mock_config = get_mock_config()506 import_paths = mock_config["paths"]["imports"]507 export_paths = mock_config["paths"]["exports"]508 inv_item = fake_inventory_item()509 supp_item = fake_supplier_item(inv_item)510 self.seed([511 inv_item,512 supp_item,513 ])514 mock_import_missing_images_report.return_value = [inv_item]515 command = Commands.fetch_images(mock_config)516 command.db_session = self.db_session517 command()518 mock_import_data.assert_called_with(command.db_session, import_paths, [519 InventoryItem,...

Full Screen

Full Screen

cert_manager_test.py

Source:cert_manager_test.py Github

copy

Full Screen

1"""Tests for certbot.cert_manager."""2# pylint: disable=protected-access3import os4import re5import shutil6import tempfile7import unittest8import configobj9import mock10from certbot import configuration11from certbot import errors12from certbot.display import util as display_util13from certbot.storage import ALL_FOUR14from certbot.tests import storage_test15from certbot.tests import util as test_util16class BaseCertManagerTest(unittest.TestCase):17 """Base class for setting up Cert Manager tests.18 """19 def setUp(self):20 self.tempdir = tempfile.mkdtemp()21 os.makedirs(os.path.join(self.tempdir, "renewal"))22 self.cli_config = configuration.NamespaceConfig(mock.MagicMock(23 config_dir=self.tempdir,24 work_dir=self.tempdir,25 logs_dir=self.tempdir,26 quiet=False,27 ))28 self.domains = {29 "example.org": None,30 "other.com": os.path.join(self.tempdir, "specialarchive")31 }32 self.configs = dict((domain, self._set_up_config(domain, self.domains[domain]))33 for domain in self.domains)34 # We also create a file that isn't a renewal config in the same35 # location to test that logic that reads in all-and-only renewal36 # configs will ignore it and NOT attempt to parse it.37 junk = open(os.path.join(self.tempdir, "renewal", "IGNORE.THIS"), "w")38 junk.write("This file should be ignored!")39 junk.close()40 def _set_up_config(self, domain, custom_archive):41 # TODO: maybe provide NamespaceConfig.make_dirs?42 # TODO: main() should create those dirs, c.f. #90243 os.makedirs(os.path.join(self.tempdir, "live", domain))44 config = configobj.ConfigObj()45 if custom_archive is not None:46 os.makedirs(custom_archive)47 config["archive_dir"] = custom_archive48 else:49 os.makedirs(os.path.join(self.tempdir, "archive", domain))50 for kind in ALL_FOUR:51 config[kind] = os.path.join(self.tempdir, "live", domain,52 kind + ".pem")53 config.filename = os.path.join(self.tempdir, "renewal",54 domain + ".conf")55 config.write()56 return config57 def tearDown(self):58 shutil.rmtree(self.tempdir)59class UpdateLiveSymlinksTest(BaseCertManagerTest):60 """Tests for certbot.cert_manager.update_live_symlinks61 """62 def test_update_live_symlinks(self):63 """Test update_live_symlinks"""64 # pylint: disable=too-many-statements65 # create files with incorrect symlinks66 from certbot import cert_manager67 archive_paths = {}68 for domain in self.domains:69 custom_archive = self.domains[domain]70 if custom_archive is not None:71 archive_dir_path = custom_archive72 else:73 archive_dir_path = os.path.join(self.tempdir, "archive", domain)74 archive_paths[domain] = dict((kind,75 os.path.join(archive_dir_path, kind + "1.pem")) for kind in ALL_FOUR)76 for kind in ALL_FOUR:77 live_path = self.configs[domain][kind]78 archive_path = archive_paths[domain][kind]79 open(archive_path, 'a').close()80 # path is incorrect but base must be correct81 os.symlink(os.path.join(self.tempdir, kind + "1.pem"), live_path)82 # run update symlinks83 cert_manager.update_live_symlinks(self.cli_config)84 # check that symlinks go where they should85 prev_dir = os.getcwd()86 try:87 for domain in self.domains:88 for kind in ALL_FOUR:89 os.chdir(os.path.dirname(self.configs[domain][kind]))90 self.assertEqual(91 os.path.realpath(os.readlink(self.configs[domain][kind])),92 os.path.realpath(archive_paths[domain][kind]))93 finally:94 os.chdir(prev_dir)95class DeleteTest(storage_test.BaseRenewableCertTest):96 """Tests for certbot.cert_manager.delete97 """98 @test_util.patch_get_utility()99 @mock.patch('certbot.cert_manager.lineage_for_certname')100 @mock.patch('certbot.storage.delete_files')101 def test_delete(self, mock_delete_files, mock_lineage_for_certname, unused_get_utility):102 """Test delete"""103 mock_lineage_for_certname.return_value = self.test_rc104 self.cli_config.certname = "example.org"105 from certbot import cert_manager106 cert_manager.delete(self.cli_config)107 self.assertTrue(mock_delete_files.called)108class CertificatesTest(BaseCertManagerTest):109 """Tests for certbot.cert_manager.certificates110 """111 def _certificates(self, *args, **kwargs):112 from certbot.cert_manager import certificates113 return certificates(*args, **kwargs)114 @mock.patch('certbot.cert_manager.logger')115 @test_util.patch_get_utility()116 def test_certificates_parse_fail(self, mock_utility, mock_logger):117 self._certificates(self.cli_config)118 self.assertTrue(mock_logger.warning.called) #pylint: disable=no-member119 self.assertTrue(mock_utility.called)120 @mock.patch('certbot.cert_manager.logger')121 @test_util.patch_get_utility()122 def test_certificates_quiet(self, mock_utility, mock_logger):123 self.cli_config.quiet = True124 self._certificates(self.cli_config)125 self.assertFalse(mock_utility.notification.called)126 self.assertTrue(mock_logger.warning.called) #pylint: disable=no-member127 @mock.patch('certbot.cert_manager.logger')128 @test_util.patch_get_utility()129 @mock.patch("certbot.storage.RenewableCert")130 @mock.patch('certbot.cert_manager._report_human_readable')131 def test_certificates_parse_success(self, mock_report, mock_renewable_cert,132 mock_utility, mock_logger):133 mock_report.return_value = ""134 self._certificates(self.cli_config)135 self.assertFalse(mock_logger.warning.called) #pylint: disable=no-member136 self.assertTrue(mock_report.called)137 self.assertTrue(mock_utility.called)138 self.assertTrue(mock_renewable_cert.called)139 @mock.patch('certbot.cert_manager.logger')140 @test_util.patch_get_utility()141 def test_certificates_no_files(self, mock_utility, mock_logger):142 tempdir = tempfile.mkdtemp()143 cli_config = configuration.NamespaceConfig(mock.MagicMock(144 config_dir=tempdir,145 work_dir=tempdir,146 logs_dir=tempdir,147 quiet=False,148 ))149 os.makedirs(os.path.join(tempdir, "renewal"))150 self._certificates(cli_config)151 self.assertFalse(mock_logger.warning.called) #pylint: disable=no-member152 self.assertTrue(mock_utility.called)153 shutil.rmtree(tempdir)154 @mock.patch('certbot.cert_manager.ocsp.RevocationChecker.ocsp_revoked')155 def test_report_human_readable(self, mock_revoked):156 mock_revoked.return_value = None157 from certbot import cert_manager158 import datetime, pytz159 expiry = pytz.UTC.fromutc(datetime.datetime.utcnow())160 cert = mock.MagicMock(lineagename="nameone")161 cert.target_expiry = expiry162 cert.names.return_value = ["nameone", "nametwo"]163 cert.is_test_cert = False164 parsed_certs = [cert]165 # pylint: disable=protected-access166 get_report = lambda: cert_manager._report_human_readable(mock_config, parsed_certs)167 mock_config = mock.MagicMock(certname=None, lineagename=None)168 # pylint: disable=protected-access169 out = get_report()170 self.assertTrue("INVALID: EXPIRED" in out)171 cert.target_expiry += datetime.timedelta(hours=2)172 # pylint: disable=protected-access173 out = get_report()174 self.assertTrue('1 hour(s)' in out)175 self.assertTrue('VALID' in out and not 'INVALID' in out)176 cert.target_expiry += datetime.timedelta(days=1)177 # pylint: disable=protected-access178 out = get_report()179 self.assertTrue('1 day' in out)180 self.assertFalse('under' in out)181 self.assertTrue('VALID' in out and not 'INVALID' in out)182 cert.target_expiry += datetime.timedelta(days=2)183 # pylint: disable=protected-access184 out = get_report()185 self.assertTrue('3 days' in out)186 self.assertTrue('VALID' in out and not 'INVALID' in out)187 cert.is_test_cert = True188 mock_revoked.return_value = True189 out = get_report()190 self.assertTrue('INVALID: TEST_CERT, REVOKED' in out)191 cert = mock.MagicMock(lineagename="indescribable")192 cert.target_expiry = expiry193 cert.names.return_value = ["nameone", "thrice.named"]194 cert.is_test_cert = True195 parsed_certs.append(cert)196 out = get_report()197 self.assertEqual(len(re.findall("INVALID:", out)), 2)198 mock_config.domains = ["thrice.named"]199 out = get_report()200 self.assertEqual(len(re.findall("INVALID:", out)), 1)201 mock_config.domains = ["nameone"]202 out = get_report()203 self.assertEqual(len(re.findall("INVALID:", out)), 2)204 mock_config.certname = "indescribable"205 out = get_report()206 self.assertEqual(len(re.findall("INVALID:", out)), 1)207 mock_config.certname = "horror"208 out = get_report()209 self.assertEqual(len(re.findall("INVALID:", out)), 0)210class SearchLineagesTest(BaseCertManagerTest):211 """Tests for certbot.cert_manager._search_lineages."""212 @mock.patch('certbot.util.make_or_verify_dir')213 @mock.patch('certbot.storage.renewal_conf_files')214 @mock.patch('certbot.storage.RenewableCert')215 def test_cert_storage_error(self, mock_renewable_cert, mock_renewal_conf_files,216 mock_make_or_verify_dir):217 mock_renewal_conf_files.return_value = ["badfile"]218 mock_renewable_cert.side_effect = errors.CertStorageError219 from certbot import cert_manager220 # pylint: disable=protected-access221 self.assertEqual(cert_manager._search_lineages(self.cli_config, lambda x: x, "check"),222 "check")223 self.assertTrue(mock_make_or_verify_dir.called)224class LineageForCertnameTest(BaseCertManagerTest):225 """Tests for certbot.cert_manager.lineage_for_certname"""226 @mock.patch('certbot.util.make_or_verify_dir')227 @mock.patch('certbot.storage.renewal_file_for_certname')228 @mock.patch('certbot.storage.RenewableCert')229 def test_found_match(self, mock_renewable_cert, mock_renewal_conf_file,230 mock_make_or_verify_dir):231 mock_renewal_conf_file.return_value = "somefile.conf"232 mock_match = mock.Mock(lineagename="example.com")233 mock_renewable_cert.return_value = mock_match234 from certbot import cert_manager235 self.assertEqual(cert_manager.lineage_for_certname(self.cli_config, "example.com"),236 mock_match)237 self.assertTrue(mock_make_or_verify_dir.called)238 @mock.patch('certbot.util.make_or_verify_dir')239 @mock.patch('certbot.storage.renewal_file_for_certname')240 def test_no_match(self, mock_renewal_conf_file,241 mock_make_or_verify_dir):242 mock_renewal_conf_file.return_value = "other.com.conf"243 from certbot import cert_manager244 self.assertEqual(cert_manager.lineage_for_certname(self.cli_config, "example.com"),245 None)246 self.assertTrue(mock_make_or_verify_dir.called)247class DomainsForCertnameTest(BaseCertManagerTest):248 """Tests for certbot.cert_manager.domains_for_certname"""249 @mock.patch('certbot.util.make_or_verify_dir')250 @mock.patch('certbot.storage.renewal_file_for_certname')251 @mock.patch('certbot.storage.RenewableCert')252 def test_found_match(self, mock_renewable_cert, mock_renewal_conf_file,253 mock_make_or_verify_dir):254 mock_renewal_conf_file.return_value = "somefile.conf"255 mock_match = mock.Mock(lineagename="example.com")256 domains = ["example.com", "example.org"]257 mock_match.names.return_value = domains258 mock_renewable_cert.return_value = mock_match259 from certbot import cert_manager260 self.assertEqual(cert_manager.domains_for_certname(self.cli_config, "example.com"),261 domains)262 self.assertTrue(mock_make_or_verify_dir.called)263 @mock.patch('certbot.util.make_or_verify_dir')264 @mock.patch('certbot.storage.renewal_file_for_certname')265 def test_no_match(self, mock_renewal_conf_file,266 mock_make_or_verify_dir):267 mock_renewal_conf_file.return_value = "somefile.conf"268 from certbot import cert_manager269 self.assertEqual(cert_manager.domains_for_certname(self.cli_config, "other.com"),270 None)271 self.assertTrue(mock_make_or_verify_dir.called)272class RenameLineageTest(BaseCertManagerTest):273 """Tests for certbot.cert_manager.rename_lineage"""274 def setUp(self):275 super(RenameLineageTest, self).setUp()276 self.mock_config = configuration.NamespaceConfig(277 namespace=mock.MagicMock(278 config_dir=self.tempdir,279 work_dir=self.tempdir,280 logs_dir=self.tempdir,281 certname="example.org",282 new_certname="after",283 )284 )285 def _call(self, *args, **kwargs):286 from certbot import cert_manager287 return cert_manager.rename_lineage(*args, **kwargs)288 @mock.patch('certbot.storage.renewal_conf_files')289 @test_util.patch_get_utility()290 def test_no_certname(self, mock_get_utility, mock_renewal_conf_files):291 mock_config = mock.Mock(certname=None, new_certname="two")292 # if not choices293 mock_renewal_conf_files.return_value = []294 self.assertRaises(errors.Error, self._call, mock_config)295 mock_renewal_conf_files.return_value = ["one.conf"]296 util_mock = mock.Mock()297 util_mock.menu.return_value = (display_util.CANCEL, 0)298 mock_get_utility.return_value = util_mock299 self.assertRaises(errors.Error, self._call, mock_config)300 util_mock.menu.return_value = (display_util.OK, -1)301 self.assertRaises(errors.Error, self._call, mock_config)302 @test_util.patch_get_utility()303 def test_no_new_certname(self, mock_get_utility):304 mock_config = mock.Mock(certname="one", new_certname=None)305 util_mock = mock.Mock()306 util_mock.input.return_value = (display_util.CANCEL, "name")307 mock_get_utility.return_value = util_mock308 self.assertRaises(errors.Error, self._call, mock_config)309 util_mock = mock.Mock()310 util_mock.input.return_value = (display_util.OK, None)311 mock_get_utility.return_value = util_mock312 self.assertRaises(errors.Error, self._call, mock_config)313 @test_util.patch_get_utility()314 @mock.patch('certbot.cert_manager.lineage_for_certname')315 def test_no_existing_certname(self, mock_lineage_for_certname, unused_get_utility):316 mock_config = mock.Mock(certname="one", new_certname="two")317 mock_lineage_for_certname.return_value = None318 self.assertRaises(errors.ConfigurationError,319 self._call, mock_config)320 @test_util.patch_get_utility()321 @mock.patch("certbot.storage.RenewableCert._check_symlinks")322 def test_rename_cert(self, mock_check, unused_get_utility):323 mock_check.return_value = True324 mock_config = self.mock_config325 self._call(mock_config)326 from certbot import cert_manager327 updated_lineage = cert_manager.lineage_for_certname(mock_config, mock_config.new_certname)328 self.assertTrue(updated_lineage is not None)329 self.assertEqual(updated_lineage.lineagename, mock_config.new_certname)330 @test_util.patch_get_utility()331 @mock.patch("certbot.storage.RenewableCert._check_symlinks")332 def test_rename_cert_interactive_certname(self, mock_check, mock_get_utility):333 mock_check.return_value = True334 mock_config = self.mock_config335 mock_config.certname = None336 util_mock = mock.Mock()337 util_mock.menu.return_value = (display_util.OK, 0)338 mock_get_utility.return_value = util_mock339 self._call(mock_config)340 from certbot import cert_manager341 updated_lineage = cert_manager.lineage_for_certname(mock_config, mock_config.new_certname)342 self.assertTrue(updated_lineage is not None)343 self.assertEqual(updated_lineage.lineagename, mock_config.new_certname)344 @test_util.patch_get_utility()345 @mock.patch("certbot.storage.RenewableCert._check_symlinks")346 def test_rename_cert_bad_new_certname(self, mock_check, unused_get_utility):347 mock_check.return_value = True348 mock_config = self.mock_config349 # for example, don't rename to existing certname350 mock_config.new_certname = "example.org"351 self.assertRaises(errors.ConfigurationError, self._call, mock_config)352 mock_config.new_certname = "one{0}two".format(os.path.sep)353 self.assertRaises(errors.ConfigurationError, self._call, mock_config)354class DuplicativeCertsTest(storage_test.BaseRenewableCertTest):355 """Test to avoid duplicate lineages."""356 def setUp(self):357 super(DuplicativeCertsTest, self).setUp()358 self.config.write()359 self._write_out_ex_kinds()360 def tearDown(self):361 shutil.rmtree(self.tempdir)362 @mock.patch('certbot.util.make_or_verify_dir')363 def test_find_duplicative_names(self, unused_makedir):364 from certbot.cert_manager import find_duplicative_certs365 test_cert = test_util.load_vector('cert-san.pem')366 with open(self.test_rc.cert, 'wb') as f:367 f.write(test_cert)368 # No overlap at all369 result = find_duplicative_certs(370 self.cli_config, ['wow.net', 'hooray.org'])371 self.assertEqual(result, (None, None))372 # Totally identical373 result = find_duplicative_certs(374 self.cli_config, ['example.com', 'www.example.com'])375 self.assertTrue(result[0].configfile.filename.endswith('example.org.conf'))376 self.assertEqual(result[1], None)377 # Superset378 result = find_duplicative_certs(379 self.cli_config, ['example.com', 'www.example.com', 'something.new'])380 self.assertEqual(result[0], None)381 self.assertTrue(result[1].configfile.filename.endswith('example.org.conf'))382 # Partial overlap doesn't count383 result = find_duplicative_certs(384 self.cli_config, ['example.com', 'something.new'])385 self.assertEqual(result, (None, None))386if __name__ == "__main__":...

Full Screen

Full Screen

perseo_mock.py

Source:perseo_mock.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3#4# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U5#6# This file is part of perseo_mock7#8# perseo_mock is free software: you can redistribute it and/or9# modify it under the terms of the GNU Affero General Public License as10# published by the Free Software Foundation, either version 3 of the License,11# or (at your option) any later version.12#13# perseo_mock is distributed in the hope that it will be useful,14# but WITHOUT ANY WARRANTY; without even the implied warranty of15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.16# See the GNU Affero General Public License for more details.17#18# You should have received a copy of the GNU Affero General Public19# License along with perseo_mock.20# If not, seehttp://www.gnu.org/licenses/.21#22# For those usages not covered by the GNU Affero General Public License23# please contact with:24# Ivan Arias (ivan.ariasleon@telefonica.com)25#26import BaseHTTPServer27import smtpd28import asyncore29import time30import mock_config31import sys32import json33from multiprocessing import Process, Manager34class FakeSMTPServer(smtpd.SMTPServer):35 """A Fake smtp server"""36 def __init__(*args, **kwargs):37 """38 constructor39 """40 smtpd.SMTPServer.__init__(*args, **kwargs)41 def process_message(self, peer, mailfrom, rcpttos, data):42 """43 receive a email44 """45 body_email[mock_config.SMTP_COUNTER] += 146 body_email[mock_config.SMTP_PEER] = peer47 body_email[mock_config.SMTP_MAILFROM] = mailfrom48 body_email[mock_config.SMTP_RCPTTOS] = rcpttos49 body_email[mock_config.SMTP_DATA] = data50 print mock_config.ONE_LINE51 print mock_config.SMTP_RECEIVING_MSG_FROM, body_email[mock_config.SMTP_PEER]52 print mock_config.SMTP_MSG_ADDRESSED_TO, body_email[mock_config.SMTP_RCPTTOS]53 print mock_config.SMTP_MSG_LENGTH, len(body_email[mock_config.SMTP_DATA])54 if mock_config.MORE_INFO: # -i option55 print mock_config.SMTP_COUNTER, str(body_email[mock_config.SMTP_COUNTER])56 print mock_config.SMTP_MSG_ADDRESSED_FROM, body_email[mock_config.SMTP_MAILFROM]57 print mock_config.SMTP_DATA_INFO, str(body_email[mock_config.SMTP_DATA])58body_sms = mock_config.INITIAL_SMS_MSG59body_update = mock_config.INITIAL_UPDATE_MSG60body_post = mock_config.INITIAL_POST_MSG61sms_number = 062update_number = 063post_number = 064class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):65 """A http server"""66 def do_POST(self):67 """68 Respond to a POST request.69 """70 global body_sms, body_update, body_post, sms_number, update_number, post_number71 try:72 # POST response - socket hang up73 self.send_response(mock_config.OK)74 self.send_header(mock_config.CONTENT_TYPE, mock_config.APPLICATION_JSON)75 self.send_header(mock_config.CONTENT_LENGTH, 0)76 self.end_headers()77 self.wfile.write("")78 # get the request body79 length = int(self.headers[mock_config.CONTENT_LENGTH])80 body = self.rfile.read(length)81 print mock_config.ONE_LINE82 if self.path.find(mock_config.SEND_SMS) >= 0: # /send/sms83 body_sms = str(body)84 sms_number += 185 print body_sms86 if mock_config.MORE_INFO: # -i option87 print "sms counter: {0}".format(str(sms_number))88 elif self.path.find(mock_config.SEND_UPDATE) >= 0: # /send/update89 body_update = str(body)90 update_number += 191 print body_update92 if mock_config.MORE_INFO: # -i option93 print "update counter: {0}".format(str(update_number))94 else: # /send/http/post95 body_post = str(body)96 post_number += 197 print body_post98 if mock_config.MORE_INFO: # -i option99 print "http counter (last request: POST): {0}".format(str(post_number))100 except Exception, e:101 print "WARN - " + str(e)102 def do_GET(self):103 """104 Respond to a GET request.105 """106 global body_sms, body_update, sms_number, update_number, body_post, post_number107 body_temp = u''108 # gets109 self.send_response(mock_config.OK)110 self.send_header(mock_config.CONTENT_TYPE, mock_config.APPLICATION_JSON)111 if self.path.find(mock_config.GET_EMAIL) >= 0: # /get/email112 body_temp = json.dumps(dict(body_email))113 elif self.path.find(mock_config.GET_SMS) >= 0: # /get/sms114 body_temp = body_sms115 elif self.path.find(mock_config.GET_UPDATE) >= 0: # /get/update116 body_temp = body_update117 elif self.path.find(mock_config.GET_POST) >= 0: # /get/post118 body_temp = body_post119 # counters120 elif self.path.find(mock_config.COUNTER_EMAIL) >= 0: # /counter/email121 body_temp = "email counter: " + str(body_email[mock_config.SMTP_COUNTER])122 elif self.path.find(mock_config.COUNTER_SMS) >= 0: # /counter/sms123 body_temp = "sms counter: " + str(sms_number)124 elif self.path.find(mock_config.COUNTER_UPDATE) >= 0: # /counter/update125 body_temp = "update counter: " + str(update_number)126 elif self.path.find(mock_config.COUNTER_POST) >= 0: # /counter/post127 body_temp = "http counter: " + str(post_number)128 else: # /send/http_get129 post_number += 1130 body_temp = "http counter (last request: GET): {0}".format(str(post_number))131 if mock_config.MORE_INFO: # -i option132 print body_temp133 self.send_header(mock_config.CONTENT_LENGTH, len(str(body_temp)))134 self.end_headers()135 self.wfile.write(str(body_temp))136 def do_PUT(self):137 """138 Respond to a PUT request.139 """140 body = "%s counter is reset..." % self.path[len("/reset/"):]141 global sms_number, update_number, body_sms, body_update, post_number, body_post142 self.send_response(mock_config.OK)143 if self.path.find(mock_config.RESET_EMAIL) >= 0: # /reset/email144 body_email[mock_config.SMTP_COUNTER] = 0145 body_email[mock_config.SMTP_DATA] = mock_config.INITIAL_EMAIL_MSG146 elif self.path.find(mock_config.RESET_SMS) >= 0: # /reset/sms147 sms_number = 0148 body_sms = mock_config.INITIAL_SMS_MSG149 elif self.path.find(mock_config.RESET_UPDATE) >= 0: # /reset/update150 update_number = 0151 body_update = mock_config.INITIAL_UPDATE_MSG152 elif self.path.find(mock_config.RESET_POST) >= 0: # /reset/post153 post_number = 0154 body_post = mock_config.INITIAL_POST_MSG155 else: # /send/http_put156 length = int(self.headers[mock_config.CONTENT_LENGTH])157 body = self.rfile.read(length)158 body_post = str(body)159 post_number += 1160 print body_post161 if mock_config.MORE_INFO: # -i option162 print "http counter (last request: PUT): {0}".format(str(post_number))163 self.send_header(mock_config.CONTENT_LENGTH, len(body))164 self.end_headers()165 self.wfile.write(body)166 def do_PATCH(self):167 """168 Respond to a PATCH request.169 """170 global sms_number, update_number, body_sms, body_update, post_number, body_post171 self.send_response(mock_config.OK)172 # /send/http_patch173 length = int(self.headers[mock_config.CONTENT_LENGTH])174 body = self.rfile.read(length)175 body_post = str(body)176 post_number += 1177 print body_post178 if mock_config.MORE_INFO: # -i option179 print "http counter (last request: PATCH): {0}".format(str(post_number))180 self.send_header(mock_config.CONTENT_LENGTH, len(body))181 self.end_headers()182 self.wfile.write(body)183 def do_DELETE(self):184 """185 Respond to a GET request.186 """187 global body_sms, body_update, sms_number, update_number, body_post, post_number188 body_temp = u''189 # gets190 self.send_response(mock_config.OK)191 self.send_header(mock_config.CONTENT_TYPE, mock_config.APPLICATION_JSON)192 # /send/http_delete193 post_number += 1194 body_temp = "http counter (last request: DELETE): {0}".format(str(post_number))195 if mock_config.MORE_INFO: # -i option196 print body_temp197 self.send_header(mock_config.CONTENT_LENGTH, len(str(body_temp)))198 self.end_headers()199 self.wfile.write(str(body_temp))200if __name__ == "__main__":201 mock_config.configuration(sys.argv)202 smtp_server = FakeSMTPServer((mock_config.SMTP_BIND, mock_config.SMTP_PORT), None)203 server_class = BaseHTTPServer.HTTPServer204 httpd = server_class((mock_config.HTTP_BIND, mock_config.HTTP_PORT), MyHandler)205 print "Servers Starts at %s " % (time.asctime())206 try:207 manager = Manager() # share between process208 body_email = manager.dict()209 body_email[mock_config.SMTP_COUNTER] = 0210 body_email[mock_config.SMTP_DATA] = mock_config.INITIAL_EMAIL_MSG211 p2 = Process(target=asyncore.loop)212 p1 = Process(target=httpd.serve_forever)213 p2.start()214 p1.start()215 p1.join()216 p2.join()217 except KeyboardInterrupt:218 p1.terminate()219 p2.terminate()220 except:221 print mock_config.ERROR + mock_config.MULTIPROCESSING_ERROR_MSG222 finally:223 smtp_server.close()224 httpd.server_close()...

Full Screen

Full Screen

metircs_controller_test.py

Source:metircs_controller_test.py Github

copy

Full Screen

1import unittest2import os3from unittest.mock import MagicMock4from src import metircs_controller5from src import config6class TestMetricsController(unittest.TestCase):7 def test_route_metircs(self):8 route = "/metircs"9 mock_http_response = MockHttpResponse()10 mock_service_factory = MockServiceFactory()11 mock_config = config.Config()12 mock_config.get_namespace = MagicMock(return_value=None)13 mock_config.get_service = MagicMock(return_value=None)14 controller = metircs_controller.MetricsController(mock_service_factory, mock_config)15 controller.route(mock_http_response, route)16 self.assertEqual(200, mock_http_response.status_code)17 self.assertEqual(_response(), mock_http_response.content)18 self.assertEqual("application/json", mock_http_response.content_type)19 def test_route_metircs_with_env_set(self):20 route = "/dev/metric/metircs"21 mock_http_response = MockHttpResponse()22 mock_service_factory = MockServiceFactory()23 mock_config = config.Config()24 mock_config.get_namespace = MagicMock(return_value="dev")25 mock_config.get_service = MagicMock(return_value="metric")26 controller = metircs_controller.MetricsController(mock_service_factory, mock_config)27 controller.route(mock_http_response, route)28 self.assertEqual(200, mock_http_response.status_code)29 self.assertEqual(_response(), mock_http_response.content)30 self.assertEqual("application/json", mock_http_response.content_type)31 32 def test_route_404(self):33 route = "/willneverfind"34 mock_http_response = MockHttpResponse()35 mock_service_factory = MockServiceFactory()36 mock_config = config.Config()37 mock_config.get_namespace = MagicMock(return_value=None)38 mock_config.get_service = MagicMock(return_value=None)39 controller = metircs_controller.MetricsController(mock_service_factory, mock_config)40 controller.route(mock_http_response, route)41 self.assertEqual(404, mock_http_response.status_code)42 self.assertEqual("NOT FOUND", mock_http_response.content)43 self.assertEqual("text/plain", mock_http_response.content_type)44 def test_route_health(self):45 route = "/health"46 mock_http_response = MockHttpResponse()47 mock_service_factory = MockServiceFactory()48 mock_config = config.Config()49 mock_config.get_namespace = MagicMock(return_value=None)50 mock_config.get_service = MagicMock(return_value=None)51 controller = metircs_controller.MetricsController(mock_service_factory, mock_config)52 controller.route(mock_http_response, route)53 self.assertEqual(200, mock_http_response.status_code)54 self.assertEqual(str({"status" : "OK"}), mock_http_response.content)55 self.assertEqual("application/json", mock_http_response.content_type)56 def test_route_health_with_env(self):57 route = "/dev/metric/health"58 mock_http_response = MockHttpResponse()59 mock_service_factory = MockServiceFactory()60 mock_config = config.Config()61 mock_config.get_namespace = MagicMock(return_value="dev")62 mock_config.get_service = MagicMock(return_value="metric")63 controller = metircs_controller.MetricsController(mock_service_factory, mock_config)64 controller.route(mock_http_response, route)65 self.assertEqual(200, mock_http_response.status_code)66 self.assertEqual(str({"status" : "OK"}), mock_http_response.content)67 self.assertEqual("application/json", mock_http_response.content_type)68def _response() -> str:69 return str({ 70 "cpu" : { 71 "usage" : 5072 }, "ram" : {73 "usage" : 4074 }75 })76class MockService:77 def get_metircs_package(self):78 return _response()79 def get_health_package(self):80 return str({"status" : "OK"})81 def get_404_package(self):82 return str("NOT FOUND")83class MockServiceFactory:84 def build(self, option):85 return MockService()86class MockHttpResponse:87 status_code = 088 content_type = ""89 content = ""90 def set_status_code(self, new_status_code):91 self.status_code = new_status_code92 def set_content_type(self, new_content_type):93 self.content_type = new_content_type94 def set_status_content(self, new_content):95 self.content = new_content96if __name__ == '__main__':...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful