Best Python code snippet using green
test_result.py
Source:test_result.py  
...30        """31        btr = BaseTestResult(None, None)32        pt = ProtoTest()33        o = "some output"34        btr.recordStdout(pt, o)35        self.assertEqual(btr.stdout_output[pt], o)36    def test_stdoutNoOutput(self):37        """38        recordStdout ignores empty output sent to it39        """40        btr = BaseTestResult(None, None)41        pt = ProtoTest()42        btr.recordStdout(pt, '')43        self.assertEqual(btr.stdout_output, {})44    def test_displayStdout(self):45        """46        displayStdout displays captured stdout47        """48        stream = StringIO()49        noise = "blah blah blah"50        btr = BaseTestResult(stream, Colors(False))51        pt = ProtoTest()52        btr.stdout_output[pt] = noise53        btr.displayStdout(pt)54        self.assertIn(noise, stream.getvalue())55    def test_stderrErrput(self):56        """57        recordStderr records errput.58        """59        btr = BaseTestResult(None, None)60        pt = ProtoTest()61        o = "some errput"62        btr.recordStderr(pt, o)63        self.assertEqual(btr.stderr_errput[pt], o)64    def test_stderrNoErrput(self):65        """66        recordStderr ignores empty errput sent to it67        """68        btr = BaseTestResult(None, None)69        pt = ProtoTest()70        btr.recordStderr(pt, '')71        self.assertEqual(btr.stderr_errput, {})72    def test_displayStderr(self):73        """74        displayStderr displays captured stderr75        """76        stream = StringIO()77        noise = "blah blah blah"78        btr = BaseTestResult(stream, Colors(False))79        pt = ProtoTest()80        btr.stderr_errput[pt] = noise81        btr.displayStderr(pt)82        self.assertIn(noise, stream.getvalue())83class TestProtoTestResult(unittest.TestCase):84    def test_addSuccess(self):85        """86        addSuccess adds a test correctly87        """88        ptr = ProtoTestResult()89        test = proto_test(MagicMock())90        ptr.addSuccess(test)91        self.assertEqual(test, ptr.passing[0])92    def test_addError(self):93        """94        addError adds a test and error correctly95        """96        ptr = ProtoTestResult()97        test = proto_test(MagicMock())98        try:99            raise Exception100        except:101            err = proto_error(sys.exc_info())102        ptr.addError(test, err)103        self.assertEqual(test, ptr.errors[0][0])104        self.assertEqual(err, ptr.errors[0][1])105    def test_addFailure(self):106        """107        addFailure adds a test and error correctly108        """109        ptr = ProtoTestResult()110        test = proto_test(MagicMock())111        try:112            raise Exception113        except:114            err = proto_error(sys.exc_info())115        ptr.addFailure(test, err)116        self.assertEqual(test, ptr.failures[0][0])117        self.assertEqual(err, ptr.failures[0][1])118    def test_addSkip(self):119        """120        addSkip adds a test and reason correctly121        """122        ptr = ProtoTestResult()123        test = proto_test(MagicMock())124        reason = "some plausible reason"125        ptr.addSkip(test, reason)126        self.assertEqual(test, ptr.skipped[0][0])127        self.assertEqual(reason, ptr.skipped[0][1])128    def test_addExpectedFailure(self):129        """130        addExpectedFailure adds a test and error correctly131        """132        ptr = ProtoTestResult()133        test = proto_test(MagicMock())134        try:135            raise Exception136        except:137            err = proto_error(sys.exc_info())138        ptr.addExpectedFailure(test, err)139        self.assertEqual(test, ptr.expectedFailures[0][0])140        self.assertEqual(err, ptr.expectedFailures[0][1])141    def test_addUnexpectedSuccess(self):142        """143        addUnexpectedSuccess adds a test correctly144        """145        ptr = ProtoTestResult()146        test = proto_test(MagicMock())147        ptr.addUnexpectedSuccess(test)148        self.assertEqual(test, ptr.unexpectedSuccesses[0])149class TestProtoError(unittest.TestCase):150    def test_str(self):151        """152        Running a ProtoError through str() should result in a traceback string153        """154        test_str = 'noetuaoe'155        try:156            raise Exception(test_str)157        except:158            err = sys.exc_info()159        pe = proto_error(err)160        self.assertIn(test_str, str(pe))161class TestProtoTest(unittest.TestCase):162    def test_ProtoTestBlank(self):163        """164        ProtoTest can be instantiated empty165        """166        pt = ProtoTest()167        for i in ['module', 'class_name', 'docstr_part', 'method_name']:168            self.assertEqual('', getattr(pt, i, None))169    def test_str(self):170        """171        Running a ProtoTest through str() is the same as getting .dotted_name172        """173        pt = ProtoTest()174        pt.module = 'aoeusnth'175        self.assertEqual(str(pt), pt.dotted_name)176    def test_ProtoTestFromTest(self):177        """178        Passing a test into ProtoTest copies out the relevant info.179        """180        module      = 'green.test.test_result'181        class_name  = 'Small'182        docstr_part = 'stuff'183        method_name = 'test_method'184        class Small(unittest.TestCase):185            def test_method(self):186                "stuff"187        pt = ProtoTest(Small('test_method'))188        for i in ['module', 'class_name', 'docstr_part', 'method_name']:189            self.assertEqual(locals()[i], getattr(pt, i, None))190    def test_getDescription(self):191        """192        getDescription() returns what we expect for all verbose levels193        """194        # With a docstring195        class Fruit(unittest.TestCase):196            def test_stuff(self):197                'apple'198                pass199        t = proto_test(Fruit('test_stuff'))200        self.assertEqual(t.getDescription(1), '')201        self.assertEqual(t.getDescription(2), 'test_stuff')202        self.assertEqual(t.getDescription(3), 'apple')203        self.assertEqual(t.getDescription(4), 'apple')204        # Without a docstring205        class Vegetable(unittest.TestCase):206            def test_stuff(self):207                pass208        t = proto_test(Vegetable('test_stuff'))209        self.assertEqual(t.getDescription(1), '')210        self.assertEqual(t.getDescription(2), 'test_stuff')211        self.assertEqual(t.getDescription(3), 'test_stuff')212        self.assertEqual(t.getDescription(4), 'test_stuff')213    def test_newlineDocstring(self):214        """215        Docstrings starting with a newline are properly handled.216        """217        class MyTests(unittest.TestCase):218            def test_stuff(self):219                """220                tricky221                """222                pass223        test = proto_test(MyTests('test_stuff'))224        self.assertIn('tricky', test.getDescription(3))225    def test_multilineDocstring(self):226        """227        The description includes all of docstring until the first blank line.228        """229        class LongDocs(unittest.TestCase):230            def test_long(self):231                """First line is232                tricky!233                garbage234                """235                pass236        test = proto_test(LongDocs('test_long'))237        self.assertIn('tricky', test.getDescription(3))238        self.assertNotIn('garbage', test.getDescription(3))239class TestGreenTestResult(unittest.TestCase):240    def setUp(self):241        self.args = copy.deepcopy(default_args)242        self.stream = StringIO()243    def tearDown(self):244        del(self.stream)245        del(self.args)246    @patch('green.result.GreenTestResult.printErrors')247    def test_stopTestRun(self, mock_printErrors):248        """249        We ignore coverage's error about not having anything to cover.250        """251        try:252            from coverage.misc import CoverageException253        except:254            self.skipTest("Coverage needs to be installed for this test.")255        self.args.cov = MagicMock()256        self.args.cov.stop = MagicMock(257                side_effect=CoverageException('Different Exception'))258        self.args.run_coverage = True259        gtr = GreenTestResult(self.args, GreenStream(self.stream))260        gtr.startTestRun()261        self.assertRaises(CoverageException, gtr.stopTestRun)262        self.args.cov.stop = MagicMock(263                side_effect=CoverageException('No data to report'))264    def test_tryRecordingStdoutStderr(self):265        """266        Recording stdout and stderr works correctly.267        """268        gtr = GreenTestResult(self.args, GreenStream(self.stream))269        gtr.recordStdout = MagicMock()270        gtr.recordStderr = MagicMock()271        output = 'apple'272        test1 = MagicMock()273        ptr1 = MagicMock()274        ptr1.stdout_output = {test1:output}275        ptr1.stderr_errput = {}276        errput = 'banana'277        test2 = MagicMock()278        ptr2 = MagicMock()279        ptr2.stdout_output = {}280        ptr2.stderr_errput = {test2:errput}281        gtr.tryRecordingStdoutStderr(test1, ptr1)282        gtr.recordStdout.assert_called_with(test1, output)283        gtr.tryRecordingStdoutStderr(test2, ptr2)284        gtr.recordStderr.assert_called_with(test2, errput)285    def test_failfastAddError(self):286        """287        addError triggers failfast when it is set288        """289        self.args.failfast = True290        gtr = GreenTestResult(self.args, GreenStream(self.stream))291        self.assertEqual(gtr.failfast, True)292        try:293            raise Exception294        except:295            err = sys.exc_info()296        self.assertEqual(gtr.shouldStop, False)297        gtr.addError(MyProtoTest(), proto_error(err))298        self.assertEqual(gtr.shouldStop, True)299    def test_failfastAddFailure(self):300        """301        addFailure triggers failfast when it is set302        """303        self.args.failfast = True304        gtr = GreenTestResult(self.args, GreenStream(self.stream))305        self.assertEqual(gtr.failfast, True)306        try:307            raise Exception308        except:309            err = sys.exc_info()310        self.assertEqual(gtr.shouldStop, False)311        gtr.addFailure(MyProtoTest(), proto_error(err))312        self.assertEqual(gtr.shouldStop, True)313    def test_failfastAddUnexpectedSuccess(self):314        """315        addUnexpectedSuccess triggers failfast when it is set316        """317        self.args.failfast = True318        gtr = GreenTestResult(self.args, GreenStream(self.stream))319        self.assertEqual(gtr.failfast, True)320        self.assertEqual(gtr.shouldStop, False)321        gtr.addUnexpectedSuccess(MyProtoTest())322        self.assertEqual(gtr.shouldStop, True)323    def _outputFromVerboseTest(self):324        """325        Start a test with verbose = 2 and get its output.326        """327        class FakeCase(unittest.TestCase):328            def runTest(self):329                pass330        self.args.verbose = 2331        gtr = GreenTestResult(self.args, GreenStream(self.stream))332        tc = FakeCase()333        gtr.startTest(tc)334        output = self.stream.getvalue()335        return output.split('\n')336    def test_startTestVerboseTerminal(self):337        """338        startTest() contains output we expect in verbose mode on a terminal339        """340        self.stream.isatty = lambda: True341        output_lines = self._outputFromVerboseTest()342        # Output should look like (I'm not putting the termcolor formatting here)343        # green.test.test_runner344        #   FakeCase345        #     test_it346        self.assertEqual(len(output_lines), 3)347        self.assertNotIn(' ', output_lines[0])348        self.assertIn('  ', output_lines[1])349        self.assertIn('    ', output_lines[2])350    def test_startTestVerbosePipe(self):351        """352        startTest() contains output we expect in verbose mode on a pipe353        """354        self.stream.isatty = lambda: False355        output_lines = self._outputFromVerboseTest()356        # Output should look like (I'm not putting the termcolor formatting here)357        # green.test.test_runner358        #   FakeCase359        #     test_it360        self.assertEqual(len(output_lines), 3)361        self.assertNotIn(' ', output_lines[0])362        self.assertIn('  ', output_lines[1])363        # No carriage return or extra lines printed364        self.assertIn('', output_lines[2])365    def test_reportOutcome(self):366        """367        _reportOutcome contains output we expect368        """369        self.args.verbose = 1370        gtr = GreenTestResult(self.args, GreenStream(self.stream))371        gtr._reportOutcome(None, '.', lambda x: x)372        self.assertIn('.', self.stream.getvalue())373    def test_reportOutcomeCursorUp(self):374        """375        _reportOutcome moves the cursor up when it needs to376        """377        self.args.verbose = 2378        def isatty():379            return True380        gs = GreenStream(self.stream)381        gs.isatty = isatty382        gtr = GreenTestResult(self.args, gs)383        r = 'a fake reason'384        t = MagicMock()385        t.__str__.return_value = 'x' * 1000386        gtr._reportOutcome(t, '.', lambda x: x, None, r)387        self.assertIn(r, self.stream.getvalue())388        self.assertLess(len(self.stream.getvalue()), 2000)389    def test_reportOutcomeVerbose(self):390        """391        _reportOutcome contains output we expect in verbose mode392        """393        self.args.verbose = 2394        def isatty():395            return True396        gs = GreenStream(self.stream)397        gs.isatty = isatty398        gtr = GreenTestResult(self.args, gs)399        r = 'a fake reason'400        t = MagicMock()401        t.__str__.return_value = 'junk'402        gtr._reportOutcome(t, '.', lambda x: x, None, r)403        self.assertIn(r, self.stream.getvalue())404    def test_printErrorsSkipreport(self):405        """406        printErrors() prints the skip report407        """408        self.args.verbose = 1409        gtr = GreenTestResult(self.args, GreenStream(self.stream))410        pt = MyProtoTest()411        reason = "dog ate homework"412        gtr.addSkip(pt, reason)413        gtr.printErrors()414        self.assertIn(reason, self.stream.getvalue())415    def test_printErrorsStdout(self):416        """417        printErrors() prints out the captured stdout418        """419        self.args.verbose = 1420        self.args.termcolor = False421        gtr = GreenTestResult(self.args, GreenStream(self.stream))422        pt = MyProtoTest()423        output = 'this is what the test spit out to stdout'424        gtr.recordStdout(pt, output)425        gtr.addSuccess(pt)426        gtr.printErrors()427        self.assertIn(output, self.stream.getvalue())428    def test_printErrorsDots(self):429        """430        printErrors() looks correct in verbose=1 (dots) mode431        """432        try:433            raise Exception434        except:435            err = sys.exc_info()436        self.args.verbose = 1437        self.args.termcolor = False438        gtr = GreenTestResult(self.args, GreenStream(self.stream))...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!!
