Best Python code snippet using Testify_python
unittest_plugin_tests.py
Source:unittest_plugin_tests.py
1# -*- coding: utf-8 -*-2#3# This file is part of PyBuilder4#5# Copyright 2011-2020 PyBuilder Team6#7# Licensed under the Apache License, Version 2.0 (the "License");8# you may not use this file except in compliance with the License.9# You may obtain a copy of the License at10#11# http://www.apache.org/licenses/LICENSE-2.012#13# Unless required by applicable law or agreed to in writing, software14# distributed under the License is distributed on an "AS IS" BASIS,15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.16# See the License for the specific language governing permissions and17# limitations under the License.18from unittest import TestCase, TextTestRunner19from pybuilder.core import Project20from pybuilder.plugins.python.unittest_plugin import (execute_tests, execute_tests_matching,21 _instrument_result,22 _create_runner,23 _get_make_result_method_name,24 report_to_ci_server)25from pybuilder.utils import np26from test_utils import Mock, patch27__author__ = "Michael Gruber"28class PythonPathTests(TestCase):29 def setUp(self):30 self.project = Project(np("/path/to/project"))31 self.project.set_property("dir_source_unittest_python", "unittest")32 self.project.set_property("dir_source_main_python", "src")33class ExecuteTestsTests(TestCase):34 def setUp(self):35 self.mock_result = Mock()36 self.mock_logger = Mock()37 @patch("pybuilder.plugins.python.unittest_plugin.start_unittest_tool")38 @patch("unittest.TextTestRunner")39 @patch("pybuilder.plugins.python.unittest_plugin.unittest")40 @patch("pybuilder.plugins.python.unittest_plugin.discover_modules_matching")41 def test_should_discover_modules_by_suffix(self, mock_discover_modules_matching, mock_unittest, runner, tool):42 pipe = Mock()43 pipe.remote_close_cause.return_value = None44 proc = Mock()45 proc.exitcode = 046 tool.return_value = (proc, pipe)47 execute_tests(Mock(), [], runner, self.mock_logger, "/path/to/test/sources", "_tests.py", ["a", "b"])48 mock_discover_modules_matching.assert_called_with("/path/to/test/sources", "*_tests.py")49 @patch("pybuilder.plugins.python.unittest_plugin.start_unittest_tool")50 @patch("unittest.TextTestRunner")51 @patch("pybuilder.plugins.python.unittest_plugin.unittest")52 @patch("pybuilder.plugins.python.unittest_plugin.discover_modules_matching")53 def test_should_discover_modules_by_glob(self, mock_discover_modules_matching, mock_unittest, runner, tool):54 pipe = Mock()55 pipe.remote_close_cause.return_value = None56 proc = Mock()57 proc.exitcode = 058 tool.return_value = (proc, pipe)59 execute_tests_matching(Mock(), [], runner, self.mock_logger, "/path/to/test/sources", "*_tests.py", ["a", "b"])60 mock_discover_modules_matching.assert_called_with("/path/to/test/sources", "*_tests.py")61 @patch("pybuilder.plugins.python.unittest_plugin.start_unittest_tool")62 @patch("unittest.TextTestRunner")63 @patch("pybuilder.plugins.python.unittest_plugin.unittest")64 @patch("pybuilder.utils.discover_modules")65 def test_should_return_actual_test_results(self, mock_discover_modules, mock_unittest, runner, tool):66 pipe = Mock()67 pipe.remote_close_cause.return_value = None68 proc = Mock()69 proc.exitcode = 070 tool.return_value = (proc, pipe)71 mock_tests = Mock()72 mock_unittest.defaultTestLoader.loadTestsFromNames.return_value = mock_tests73 runner.return_value.run.return_value = self.mock_result74 actual, _ = execute_tests(Mock(), [], runner, self.mock_logger, "/path/to/test/sources", "_tests.py",75 ["a", "b"])76 self.assertEqual(self.mock_result, actual)77class CIServerInteractionTests(TestCase):78 @patch("pybuilder.ci_server_interaction.TestProxy")79 @patch("pybuilder.ci_server_interaction._is_running_on_teamcity")80 def test_should_report_passed_tests_to_ci_server(self, teamcity, proxy):81 teamcity.return_value = False82 project = Project("basedir")83 mock_proxy = Mock()84 proxy.return_value = mock_proxy85 mock_proxy.and_test_name.return_value = mock_proxy86 mock_proxy.__enter__ = Mock(return_value=mock_proxy)87 mock_proxy.__exit__ = Mock(return_value=False)88 result = Mock()89 result.test_names = ["test1", "test2", "test3"]90 result.failed_test_names_and_reasons = {}91 report_to_ci_server(project, result)92 mock_proxy.fails.assert_not_called()93 @patch("pybuilder.ci_server_interaction.TestProxy")94 @patch("pybuilder.ci_server_interaction._is_running_on_teamcity")95 def test_should_report_failed_tests_to_ci_server(self, teamcity, proxy):96 teamcity.return_value = False97 project = Project("basedir")98 mock_proxy = Mock()99 proxy.return_value = mock_proxy100 mock_proxy.and_test_name.return_value = mock_proxy101 mock_proxy.__enter__ = Mock(return_value=mock_proxy)102 mock_proxy.__exit__ = Mock(return_value=False)103 result = Mock()104 result.test_names = ["test1", "test2", "test3"]105 result.failed_test_names_and_reasons = {106 "test2": "Something went very wrong"107 }108 report_to_ci_server(project, result)109 mock_proxy.fails.assert_called_with("Something went very wrong")110class TestNameAwareTestResult(TestCase):111 class TestResult(object):112 def __init__(self):113 pass114 def startTest(self, test):115 pass116 def addError(self, test, err):117 pass118 def addFailure(self, test, err):119 pass120 def setUp(self):121 self.mock_test_result = _instrument_result(Mock(), TestNameAwareTestResult.TestResult())122 def test_should_append_test_name_when_running_test(self):123 self.mock_test_result.startTest("any_test_name")124 self.assertEqual(self.mock_test_result.test_names, ["any_test_name"])125 def test_should_save_exception_details_when_test_failure_occurs(self):126 self.mock_test_result.addFailure(127 "test_with_failure",128 ("type", "exception", "traceback"))129 self.assertEqual(130 self.mock_test_result.failed_test_names_and_reasons,131 {"test_with_failure": "type: exception"})132 def test_should_save_exception_details_when_test_error_occurs(self):133 self.mock_test_result.addError(134 "test_with_failure",135 ("type", "exception", "traceback"))136 self.assertEqual(137 self.mock_test_result.failed_test_names_and_reasons,138 {"test_with_failure": "type: exception"})139 def test_should_save_exception_details_when_test_failure_with_unicode_occurs(self):140 self.mock_test_result.addFailure(141 "test_with_failure",142 ("type", "exception with ünicode", "traceback"))143 self.assertEqual(144 self.mock_test_result.failed_test_names_and_reasons,145 {"test_with_failure": "type: exception with ünicode"})146 def test_should_save_exception_details_when_test_error_with_unicode_occurs(self):147 self.mock_test_result.addError(148 "test_with_failure",149 ("type", "exception with ünicode", "traceback"))150 self.assertEqual(151 self.mock_test_result.failed_test_names_and_reasons,152 {"test_with_failure": "type: exception with ünicode"})153class UnittestRunnerTest(TestCase):154 def test_create_runner_from_class(self):155 self.assertTrue(isinstance(_create_runner(TextTestRunner), TextTestRunner))156 def test_create_runner_from_str(self):157 self.assertTrue(isinstance(_create_runner("unittest.TextTestRunner"), TextTestRunner))158 def test_create_runner_from_tuple_class(self):159 self.assertTrue(isinstance(_create_runner((TextTestRunner, Mock())), TextTestRunner))160 def test_create_runner_from_tuple_str(self):161 self.assertTrue(isinstance(_create_runner(("unittest.TextTestRunner", Mock())), TextTestRunner))162 def test_get_make_result_method_name_default(self):163 self.assertEqual(_get_make_result_method_name(TextTestRunner), "_makeResult")164 def test_get_make_result_method_name_from_str(self):165 self.assertEqual(_get_make_result_method_name((TextTestRunner, "_makeResult")), "_makeResult")166 def test_get_make_result_method_name_from_method(self):167 self.assertEqual(_get_make_result_method_name((TextTestRunner, TextTestRunner._makeResult)), "_makeResult")168 def test_get_make_result_method_name_from_func(self):169 def _makeResult(self):170 pass171 self.assertEqual(_get_make_result_method_name((TextTestRunner, _makeResult)), "_makeResult")172class UnittestRunnerCompatibilityTest(TestCase):173 def test_sub_tests_issue_735(self):174 """175 Test that numbers between 0 and 5 are all between 0 and 5.176 """177 for i in range(0, 6):178 with self.subTest(i=i):179 self.assertLess(i, 6)...
test_entity_analyzer.py
Source:test_entity_analyzer.py
1import unittest2import json3import pandas as pd4from assistant_skill_analysis.utils import skills_util, lang_utils5from assistant_skill_analysis.term_analysis import entity_analyzer6class TestChi2Analyzer(unittest.TestCase):7 """8 Test for Chi2 Analyzer module9 """10 @classmethod11 def setUpClass(cls):12 test_skill_file = (13 "tests/resources/test_workspaces/skill-Customer-Care-Sample.json"14 )15 with open(test_skill_file, "r") as skill_file:16 workspace_data, workspace_vocabulary, _, _ = skills_util.extract_workspace_data(17 json.load(skill_file), lang_utils.LanguageUtility("en")18 )19 cls.workspace_df = pd.DataFrame(workspace_data)20 cls.mock_test_result = pd.DataFrame(21 {22 "correct_intent": ["intent1", "intent2"],23 "entities": [24 [25 {"entity": "entity1", "confidence": 1},26 {"entity": "entity2", "confidence": 1},27 ],28 [{"entity": "entity1", "confidence": 0.5}],29 ],30 }31 )32 def test_derive_entity_label_matrix(self):33 (34 entity_feat_mat,35 labels,36 entity_avg_conf,37 ) = entity_analyzer._derive_entity_label_matrix(38 self.mock_test_result, ["entity1", "entity2"]39 )40 self.assertEqual(entity_feat_mat[1][1], 0, "test for entity analyzer fail")41 self.assertEqual(42 entity_avg_conf["entity1"], 0.75, "test for entity analyzer fail"43 )44 def test_entity_label_correlation_analysis(self):45 entity = {"entities": [{"entity": "entity1"}, {"entity": "entity2"}]}46 entities_list = [item["entity"] for item in entity["entities"]]47 entity_label_df = entity_analyzer.entity_label_correlation_analysis(48 self.mock_test_result, entities_list, p_value=149 )50 self.assertEqual(51 entity_label_df.iloc[0]["Correlated Entities"],52 "entity2",53 "test for entity analyzer fail",54 )55 def tearDown(self):56 unittest.TestCase.tearDown(self)57if __name__ == "__main__":...
test_file_helper.py
Source:test_file_helper.py
1import os2import unittest3from pathlib import Path4import shutil5from sql_to_python.file.file_helper import unzip_to_folder, read_file, list_all_files, save_to_file6from tests.test_helper import normalize_line_endings7class TestFileHelper(unittest.TestCase):8 def setUp(self):9 self.test_file = Path("../../out/unittest/mock_test_result/000000000/lab01/ch01_t01_hello_world.py")10 self.target_dir = Path("../../out/unittest/")11 unzip_to_folder(Path("../data/mock_test_result.zip"), Path("../../out/unittest/"))12 def tearDown(self):13 shutil.rmtree(Path("../../out/unittest/"))14 def test_unzip_to_folder(self):15 print(self.test_file.absolute())16 self.assertTrue(self.test_file.is_file())17 def test_read_file(self):18 result = read_file(self.test_file)19 expect = """============================= test session starts ==============================20platform linux -- Python 3.6.1, pytest-3.7.3, py-1.5.4, pluggy-0.7.121rootdir: /tmp/ite3101_introduction_to_programming/tests/lab01, inifile:22collected 1 item23../../tmp/ite3101_introduction_to_programming/tests/lab01/test_ch01_t01_hello_world.py . [100%]24=========================== 1 passed in 0.08 seconds ===========================25"""26 self.assertEqual(expect, result)27 def test_save_to_file(self):28 expect = "testing" + os.linesep29 testfile = Path("../../out/unittest/test.txt")30 save_to_file(testfile, "testing")31 result = read_file(testfile)32 self.assertEqual(normalize_line_endings(expect), normalize_line_endings(result))33if __name__ == '__main__':...
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!!