Best Python code snippet using nose2
test_cases.py
Source:test_cases.py  
...21        a = []22        class TestClass(object):23            def test_func(self, a=a):24                a.append(1)25        case = nose.case.MethodTestCase(unbound_method(TestClass,26                                                       TestClass.test_func))27        case(res)28        assert a[0] == 129    def test_method_test_case_with_metaclass(self):30        res = unittest.TestResult()31        32        class TestType(type):33            def __new__(cls, name, bases, dct):34                return type.__new__(cls, name, bases, dct)35        a = []36        class TestClass(object):37            __metaclass__ = TestType38            def test_func(self, a=a):39                a.append(1)40        case = nose.case.MethodTestCase(unbound_method(TestClass,41                                                       TestClass.test_func))42        case(res)43        assert a[0] == 144    def test_method_test_case_fixtures(self):        45        res = unittest.TestResult()46        called = []47        class TestClass(object):48            def setup(self):49                called.append('setup')50            def teardown(self):51                called.append('teardown')52            def test_func(self):53                called.append('test')54        case = nose.case.MethodTestCase(unbound_method(TestClass,55                                                       TestClass.test_func))56        case(res)57        self.assertEqual(called, ['setup', 'test', 'teardown'])58        class TestClassFailingSetup(TestClass):59            def setup(self):60                called.append('setup')61                raise Exception("failed")62        called[:] = []63        case = nose.case.MethodTestCase(unbound_method(TestClassFailingSetup,64                                            TestClassFailingSetup.test_func))65        case(res)66        self.assertEqual(called, ['setup'])        67        class TestClassFailingTest(TestClass):68            def test_func(self):69                called.append('test')70                raise Exception("failed")71            72        called[:] = []73        case = nose.case.MethodTestCase(unbound_method(TestClassFailingTest,74                                            TestClassFailingTest.test_func))75        case(res)76        self.assertEqual(called, ['setup', 'test', 'teardown'])     77        78    def test_function_test_case_fixtures(self):79        from nose.tools import with_setup80        res = unittest.TestResult()81        called = {}82        def st():83            called['st'] = True84        def td():85            called['td'] = True86        def func_exc():87            called['func'] = True88            raise TypeError("An exception")89        func_exc = with_setup(st, td)(func_exc)90        case = nose.case.FunctionTestCase(func_exc)91        case(res)92        assert 'st' in called93        assert 'func' in called94        assert 'td' in called95    def test_failure_case(self):96        res = unittest.TestResult()97        f = nose.failure.Failure(ValueError, "No such test spam")98        f(res)99        assert res.errors100class TestNoseTestWrapper(unittest.TestCase):101    def test_case_fixtures_called(self):102        """Instance fixtures are properly called for wrapped tests"""103        res = unittest.TestResult()104        called = []105                        106        class TC(unittest.TestCase):107            def setUp(self):108                print "TC setUp %s" % self109                called.append('setUp')110            def runTest(self):111                print "TC runTest %s" % self112                called.append('runTest')113            def tearDown(self):114                print "TC tearDown %s" % self115                called.append('tearDown')116        case = nose.case.Test(TC())117        case(res)118        assert not res.errors, res.errors119        assert not res.failures, res.failures120        self.assertEqual(called, ['setUp', 'runTest', 'tearDown'])121    def test_result_proxy_used(self):122        """A result proxy is used to wrap the result for all tests"""123        class TC(unittest.TestCase):124            def runTest(self):125                raise Exception("error")126            127        ResultProxy.called[:] = []128        res = unittest.TestResult()129        config = Config()130        case = nose.case.Test(TC(), config=config,131                              resultProxy=ResultProxyFactory())132        case(res)133        assert not res.errors, res.errors134        assert not res.failures, res.failures135        calls = [ c[0] for c in ResultProxy.called ]136        self.assertEqual(calls, ['beforeTest', 'startTest', 'addError',137                                 'stopTest', 'afterTest'])138    def test_address(self):139        from nose.util import absfile, src140        class TC(unittest.TestCase):141            def runTest(self):142                raise Exception("error")143        def dummy(i):144            pass145        def test():146            pass147        class Test:148            def test(self):149                pass150            def test_gen(self):151                def tryit(i):152                    pass153                for i in range (0, 2):154                    yield tryit, i155            def try_something(self, a, b):156                pass157        fl = src(absfile(__file__))158        case = nose.case.Test(TC())159        self.assertEqual(case.address(), (fl, __name__, 'TC.runTest'))160        case = nose.case.Test(nose.case.FunctionTestCase(test))161        self.assertEqual(case.address(), (fl, __name__, 'test'))162        case = nose.case.Test(nose.case.FunctionTestCase(163            dummy, arg=(1,), descriptor=test))164        self.assertEqual(case.address(), (fl, __name__, 'test'))165        case = nose.case.Test(nose.case.MethodTestCase(166                                  unbound_method(Test, Test.test)))167        self.assertEqual(case.address(), (fl, __name__, 'Test.test'))168        case = nose.case.Test(169            nose.case.MethodTestCase(unbound_method(Test, Test.try_something),170                                     arg=(1,2,),171                                     descriptor=unbound_method(Test,172                                                               Test.test_gen)))173        self.assertEqual(case.address(),174                         (fl, __name__, 'Test.test_gen'))175        case = nose.case.Test(176            nose.case.MethodTestCase(unbound_method(Test, Test.test_gen),177                                     test=dummy, arg=(1,)))178        self.assertEqual(case.address(),179                         (fl, __name__, 'Test.test_gen'))180    def test_context(self):181        class TC(unittest.TestCase):182            def runTest(self):183                pass184        def test():185            pass186        class Test:187            def test(self):188                pass189        case = nose.case.Test(TC())190        self.assertEqual(case.context, TC)191        case = nose.case.Test(nose.case.FunctionTestCase(test))192        self.assertEqual(case.context, sys.modules[__name__])193        case = nose.case.Test(nose.case.MethodTestCase(unbound_method(Test,194                                                           Test.test)))195        self.assertEqual(case.context, Test)196    def test_short_description(self):197        class TC(unittest.TestCase):198            def test_a(self):199                """200                This is the description201                """202                pass203            def test_b(self):204                """This is the description205                """206                pass207            def test_c(self):...method_testcase_data_access.py
Source:method_testcase_data_access.py  
1from sqlalchemy.ext.declarative import declarative_base2from sqlalchemy.orm import sessionmaker3from sqlalchemy import *4from src.method_testcase import MethodTestcase5from src.testcase import TestCase6class MethodTestcaseDataAccess:7    '''This class is used to deal with the MethodTest objects8    Basically, performing operations to insert several method test objects and read MethodTest objects'''9    def __init__(self):10        engine = create_engine("mysql+mysqlconnector://root:password@localhost:3306/cbtm")11        Base = declarative_base()12        Base.metadata.bind = engine13        DBSession = sessionmaker(bind=engine)14        self.session = DBSession()15    def insert_method_testcase(self,method,testcase, module):16        # Create objects17        try:18            mt = MethodTestcase(method_name=method.name,testcase_name=testcase,method_file=method.file,testcase_module=module, method_scope=(method.scope or "UNKNOWN"))19            #Note that default value of Scope is 'UNKNOWN". This is to overcome the mysql feature where multiple NULL values are not considered duplicate.20            #We want them to be duplicate and not allowed and hence we use 'UNKNOWN' so that they are not allowed.21            self.session.add(mt)22            self.session.commit()23        except Exception as exc:24            self.session.rollback()25            print("Problem during insertion: Message = %s"%(exc))26    def get_testcases(self,method):27        # Select objects28        testcases = []29        for mtd in self.session.query(MethodTestcase).filter(MethodTestcase.method_name == method.name, MethodTestcase.method_file == method.file, MethodTestcase.method_scope == method.scope):30            tc = TestCase(mtd.testcase_name,mtd.testcase_module)31            testcases.append(tc)32        return testcases33    def get_methods(self,testcase):34        # Select objects35        methods = []36        for mtd in  self.session.query(MethodTestcase).filter(MethodTestcase.testcase_name == testcase):37            methods.append(mtd)...test_method.py
Source:test_method.py  
1from twisted.trial.unittest import TestCase2from txaws.server.method import Method3class MethodTestCase(TestCase):4    def setUp(self):5        super(MethodTestCase, self).setUp()6        self.method = Method()7    def test_defaults(self):8        """9        By default a L{Method} applies to all API versions and handles a10        single action matching its class name.11        """12        self.assertIdentical(None, self.method.actions)...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!!
