Best Python code snippet using refurb_python
unittests.py
Source:unittests.py  
1"""Unit tests"""2import unittest3from mock import Mock, patch4from iperf_command import IperfClientCommand, IperfServerCommand, IperfCommandBase5from sshpass import Sshpass, SshSubcommand6from check_errors import MyError7from test_data import *8from mtool import make_result, kill_iperf9class TestIperfCommandBase(unittest.TestCase):10    """unit tests for BaseIperfCommandBuilder class"""11        12    def test_string_to_dict(self):13        """testing of correct transformation of string to dict"""14        actual_result = IperfCommandBase().parse(OUTPUT_RESULT)15        self.assertEqual(actual_result, IPERF_PARSER_EXPECTED_RESULT)16class TestIperfServerCommandBuilder(unittest.TestCase):17    """unit tests for IperfServerCommandBuilder class"""18    def test_build_command(self):19        """testing of 'iperf -s' command building"""20        actual_result = IperfServerCommand().build_server_command()21        self.assertListEqual(actual_result, ['iperf', '-s'])22class TestIperfClientCommandBuilder(unittest.TestCase):23    """unit tests for IperfClientCommandBuilder class"""24    def test_set_server_address_ip(self):25        """testing self.server)ip setter"""26        actual_result = IperfClientCommand()\27            .set_server_ip(SERVER_IP)\28            .server_ip29        self.assertEqual(actual_result, '192.168.1.1')30    def test_set_server__address_hostname(self):31        """testing self.server_hostname setter"""32        actual_result = IperfClientCommand()\33            .set_server_hostname(SERVER_HOST)\34            .server_hostname35        self.assertEqual(actual_result, 'server')36    def test_build_command_ip(self):37        """testing of 'iperf -c 192.168.1.1' command building"""38        actual_result = IperfClientCommand()\39            .set_server_ip(SERVER_IP)\40            .build_client_command()41        self.assertListEqual(actual_result, ['iperf', '-c', '192.168.1.1'])42    def test_build_command_hostname(self):43        """testing of 'iperf -c server' command building"""44        actual_result = IperfClientCommand()\45            .set_server_hostname(SERVER_HOST)\46            .build_client_command()47        self.assertListEqual(actual_result, ['iperf', '-c', 'server'])48class TestResultBuilder(unittest.TestCase):49    """unit tests for class ResultBuilder"""50    def test_to_json(self):51        """testing of correct output in json"""52        actual_result = make_result(IPERF_PARSER_EXPECTED_RESULT,53                                      OK_MESSAGE,54                                      OK_RETURN_CODE)55        self.assertMultiLineEqual(actual_result,56                                  EXPECTED_OUTPUT_BUILDER_RESULT)57    def test_to_json_with_non_result(self):58        """testing of correct output in json when there is no result,59        message about error and error returncode"""60        actual_result = make_result(None,61                                      ERROR_MESSAGE,62                                      ERROR_RETURN_CODE)63        self.assertMultiLineEqual(actual_result, EXPECTED_OUTPUT_BUILDER_ERROR)64class TestBaseCommandExecutor(unittest.TestCase):65    """unit test for class BaseCommandExecutor"""66    def test_execute(self):67        """testing of correct output of bandwidth measurements"""68        with patch('command_executor.subprocess.Popen') as mock_subproc_popen:69            communicate_mock = Mock()70            attrs = {'communicate.return_value': (OUTPUT_RESULT,71                                                  OK_MESSAGE),72                     'returncode': OK_RETURN_CODE}73            communicate_mock.configure_mock(**attrs)74            mock_subproc_popen.return_value = communicate_mock75            actual_result = BaseCommandExecutor(COMMAND).to_execute()76            self.assertIs(actual_result.error, OK_MESSAGE)77            self.assertIs(actual_result.exit_code, OK_RETURN_CODE)78            self.assertMultiLineEqual(actual_result.output,79                                      EXECUTE_EXPECTED_RESULT)80class TestClientCommandExecutor(unittest.TestCase):81    """unit test for class ClientCommandExecutor"""82    def test_execute(self):83        """testing of correct output of bandwidth measurements"""84        with patch('command_executor.subprocess.Popen') as mock_subproc_popen:85            communicate_mock = Mock()86            attrs = {'communicate.return_value': (OUTPUT_RESULT,87                                                  OK_MESSAGE),88                     'returncode': OK_RETURN_CODE}89            communicate_mock.configure_mock(**attrs)90            mock_subproc_popen.return_value = communicate_mock91            actual_result = IperfCommandExecutor(COMMAND).to_execute()92            self.assertIs(actual_result.error, OK_MESSAGE)93            self.assertIs(actual_result.exit_code, OK_RETURN_CODE)94            self.assertDictEqual(actual_result.output,95                                 IPERF_PARSER_EXPECTED_RESULT)96class TestSshpassBaseCommandBuilder(unittest.TestCase):97    """unit tests for SshpassBaseCommandBuilder class"""98    def test_set_password(self):99        """testing self.password setter"""100        actual_result = Sshpass(COMMAND) \101            .set_password(SERVER_PASSWORD).password102        self.assertEqual(actual_result, 'QWERTY')103    def test_set_password_file(self):104        """testing self.password_file setter"""105        actual_result = Sshpass(COMMAND) \106            .set_file(PASSWORD_FILE).password_file107        self.assertEqual(actual_result, 'file.txt')108    109    def test_set_ip_address(self):110        """testing self.ip_address setter"""111        actual_result = SshCommandBuilder(SERVER_USER, COMMAND)\112            .set_ip_address(SERVER_IP)\113            .ip_address114        self.assertEqual(actual_result, '192.168.1.1')115    def test_set_hostname(self):116        """testing self.hostname setter"""117        actual_result = SshCommandBuilder(SERVER_USER, COMMAND)\118            .set_hostname(SERVER_HOST)\119            .hostname120        self.assertEqual(actual_result, 'server')121    122class TestSshCommandBuilder(unittest.TestCase):123    """unit tests for SshCommandBuilder class"""124    pass125class TestConnectionToServer(unittest.TestCase):126    """unit tests for connection_to_server() function"""127    @patch('mtool.parse_command_line_args')128    @patch('mtool.IperfCommandExecutor.to_execute')129    def test_correct_connectiom(self, mock_execute, mock_parse):130        """testing of error not occurring if exit code is 0"""131        mock_parse.return_value = ARGS_INPUT132        result = CONNECTION1133        mock_execute.return_value = result134        actual_result = connection_to_server()135        self.assertIs(actual_result.error, "")136        self.assertIs(actual_result.exit_code, 0)137        self.assertIs(actual_result.exit_code_execution, 0)138        self.assertIs(actual_result.output, IPERF_PARSER_EXPECTED_RESULT)139    @patch('mtool.parse_command_line_args')140    @patch('mtool.IperfCommandExecutor.to_execute')141    def test_connection_raises_error(self, mock_execute, mock_parse):142        """testing of error occurring if exit code is not 0"""143        mock_parse.return_value = ARGS_INPUT144        result = CONNECTION2145        mock_execute.return_value = result146        with self.assertRaises(MyError):147            connection_to_server()148    @patch('mtool.parse_command_line_args')149    @patch('mtool.IperfCommandExecutor.to_execute')150    def test_connection_raises_error_execute(self, mock_execute, mock_parse):151        """testing of error occurring if execution exit code is not 0"""152        mock_parse.return_value = ARGS_INPUT153        result = CONNECTION3154        mock_execute.return_value = result155        with self.assertRaises(MyError):156            connection_to_server()157    @patch('mtool.parse_command_line_args')158    @patch('mtool.IperfCommandExecutor.to_execute')159    def test_connection_raises_message_error(self, mock_execute, mock_parse):160        """testing of error not occurring if error message is 'Error!'"""161        mock_parse.return_value = ARGS_INPUT162        result = CONNECTION4163        mock_execute.return_value = result164        with self.assertRaises(MyError):165            connection_to_server()166class TestConnectionToClient(unittest.TestCase):167    """unit tests for connection_to_client() function"""168    @patch('mtool.parse_command_line_args')169    @patch('mtool.IperfCommandExecutor.to_execute')170    def test_correct_connection(self, mock_execute, mock_parse):171        """testing of error not occurring if exit code is 0"""172        mock_parse.return_value = ARGS_INPUT173        result = CONNECTION1174        mock_execute.return_value = result175        actual_result = connection_to_client()176        self.assertIs(actual_result.exit_code, 0)177        self.assertIs(actual_result.error, "")178        self.assertIs(actual_result.exit_code_execution, 0)179        self.assertIs(actual_result.output, IPERF_PARSER_EXPECTED_RESULT)180    @patch('mtool.parse_command_line_args')181    @patch('mtool.IperfCommandExecutor.to_execute')182    def test_connection_raises_error(self, mock_execute, mock_parse):183        """testing of error occurring if exit code is not 0"""184        mock_parse.return_value = ARGS_INPUT185        result = CONNECTION2186        mock_execute.return_value = result187        with self.assertRaises(MyError):188            connection_to_client()189    @patch('mtool.parse_command_line_args')190    @patch('mtool.IperfCommandExecutor.to_execute')191    def test_connection_raises_error_execute(self, mock_execute, mock_parse):192        """testing of error occurring if execution exit code is not 0"""193        mock_parse.return_value = ARGS_INPUT194        result = CONNECTION3195        mock_execute.return_value = result196        with self.assertRaises(MyError):197            connection_to_client()198    @patch('mtool.parse_command_line_args')199    @patch('mtool.IperfCommandExecutor.to_execute')200    def test_connection_raises_message_error(self, mock_execute, mock_parse):201        """testing of error not occurring if error message is 'Error!'"""202        mock_parse.return_value = ARGS_INPUT203        result = CONNECTION4204        mock_execute.return_value = result205        with self.assertRaises(MyError):206            connection_to_client()207    @patch('mtool.parse_command_line_args')208    @patch('mtool.IperfCommandExecutor.to_execute')209    def test_connection_raises_message_error_and_no_exit(self, mock_execute,210                                                         mock_parse):211        """testing of error occurring if error message is212        'connect failed: No route to host\n'"""213        mock_parse.return_value = ARGS_INPUT214        result = CONNECTION5215        mock_execute.return_value = result216        with self.assertRaises(MyError):217            connection_to_client()218    @patch('mtool.parse_command_line_args')219    @patch('mtool.IperfCommandExecutor.to_execute')220    def test_connection_raises_message_error_and_no_exit2(self, mock_execute,221                                                          mock_parse):222        """testing of error occurring if error message is223        'connect failed: Connection refused\n'"""224        mock_parse.return_value = ARGS_INPUT225        result = CONNECTION6226        mock_execute.return_value = result227        with self.assertRaises(MyError):228            connection_to_client()229from mtool import make_result230class TestConnectionToKillIperf(unittest.TestCase):231    """unit tests for connection_to_server_to_kill_iperf() function"""232    @patch('mtool.parse_command_line_args')233    @patch('mtool.IperfCommandExecutor.to_execute')234    def test_correct_connection(self, mock_execute, mock_parse):235        """testing of error not occurring if exit code is 0"""  236        mock_parse.return_value = ARGS_INPUT237        result = CONNECTION_KILL238        mock_execute.return_value = result239        actual_result = connection_to_server_to_kill_iperf()240        self.assertIs(actual_result.exit_code, 0)241        self.assertIs(actual_result.error, '')242        self.assertIs(actual_result.exit_code_execution, '')243        self.assertIs(actual_result.output, 0)244if __name__ == '__main__':...test_parameterparsing.py
Source:test_parameterparsing.py  
1import snykjar2def test_arg_parsing_works_for_single_dot():3    cl_args = ['.']4    args = snykjar.parse_command_line_args(cl_args)5    assert len(args.jar_path) == 16    assert args.jar_path[0] == '.'7    cl_args = ['--orgId=123', '.']8    args = snykjar.parse_command_line_args(cl_args)9    assert args.orgId == '123'10    assert len(args.jar_path) == 111    assert args.jar_path[0] == '.'12def test_arg_parsing_works_for_single_directory():13    cl_args = ['/Users/foo/some/directory']14    args = snykjar.parse_command_line_args(cl_args)15    assert len(args.jar_path) == 116    assert args.jar_path[0] == '/Users/foo/some/directory'17    cl_args = ['--orgId=123', '/Users/foo/some/directory']18    args = snykjar.parse_command_line_args(cl_args)19    assert args.orgId == '123'20    assert len(args.jar_path) == 121    assert args.jar_path[0] == '/Users/foo/some/directory'22def test_arg_parsing_works_for_single_jar():23    cl_args = ['somejar.jar']24    args = snykjar.parse_command_line_args(cl_args)25    assert len(args.jar_path) == 126    assert args.jar_path[0] == 'somejar.jar'27    cl_args = ['./somejar.jar']28    args = snykjar.parse_command_line_args(cl_args)29    assert len(args.jar_path) == 130    assert args.jar_path[0] == './somejar.jar'31    cl_args = ['/some/fully/qualified/path/somejar.jar']32    args = snykjar.parse_command_line_args(cl_args)33    assert len(args.jar_path) == 134    assert args.jar_path[0] == '/some/fully/qualified/path/somejar.jar'35    # Now with --orgId36    cl_args = ['--orgId=123', 'somejar.jar']37    args = snykjar.parse_command_line_args(cl_args)38    assert args.orgId == '123'39    assert len(args.jar_path) == 140    assert args.jar_path[0] == 'somejar.jar'41    cl_args = ['--orgId=123', './somejar.jar']42    args = snykjar.parse_command_line_args(cl_args)43    assert args.orgId == '123'44    assert len(args.jar_path) == 145    assert args.jar_path[0] == './somejar.jar'46    cl_args = ['--orgId=123', '/some/fully/qualified/path/somejar.jar']47    args = snykjar.parse_command_line_args(cl_args)48    assert args.orgId == '123'49    assert len(args.jar_path) == 150    assert args.jar_path[0] == '/some/fully/qualified/path/somejar.jar'51def test_arg_parsing_handles_multiple_jars():52    cl_args = ['somejar1.jar', 'somejar2.jar', 'somejar3.jar']53    args = snykjar.parse_command_line_args(cl_args)54    assert len(args.jar_path) == 355    assert args.jar_path[0] == cl_args[0]56    assert args.jar_path[1] == cl_args[1]57    assert args.jar_path[2] == cl_args[2]58    # Now with --orgId59    cl_args = ['--orgId=123', 'somejar1.jar', 'somejar2.jar', 'somejar3.jar']60    args = snykjar.parse_command_line_args(cl_args)61    assert args.orgId == '123'62    assert len(args.jar_path) == 363    assert args.jar_path[0] == 'somejar1.jar'64    assert args.jar_path[1] == 'somejar2.jar'65    assert args.jar_path[2] == 'somejar3.jar'66def test_arg_parsing_handles_outputPom_parameter():67    cl_args = ['--outputPom=output-pom.xml', 'somejar1.jar', 'somejar2.jar', 'somejar3.jar']68    args = snykjar.parse_command_line_args(cl_args)69    assert args.outputPom == 'output-pom.xml'70    assert len(args.jar_path) == 371    assert args.jar_path[0] == cl_args[1]72    assert args.jar_path[1] == cl_args[2]...test_main.py
Source:test_main.py  
...18    '''19    def test_valid_number_of_args(self):20        valid_args = ["main.py", "input_file.txt", "output_file.txt"] 21        try:22            main.parse_command_line_args(valid_args)23        except:24            self.fail("parse_command_line_args raised Exception unexpectedly!")25    '''26        Test for invalid params (n>3)27    '''28    def test_invalid_number_of_args(self):29        args = ["main.py", "input_file.txt", "output_file.txt", "random"] 30        self.assertRaises(InvalidCommandLineExecution,31                          main.parse_command_line_args, args)32    '''33        Test for invalid params (n<3)34    '''35    def test_invalid_number_of_args_2(self):36        args = ["main.py", "input_file.txt"] ...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!!
