Best Python code snippet using pyshould_python
tests.py
Source:tests.py  
1import unittest2from pivorm import *3import os4class TestDatabaseCreation(unittest.TestCase):5    def test_it(self):6        global db7        db = SqliteDatabase()8        db1 = SqliteDatabase()9        assert (db == db1)10class TestDatabaseConnection(TestDatabaseCreation):11    def test_it(self):12        super().test_it()13        if os.path.exists("test.db"):14            os.remove("test.db")15        db.connect("test.db")16        with self.assertRaises(Exception) as context:17            db.connect("second.db")18        self.assertTrue("connection is already open" in str(context.exception))19class TestModelDefine(TestDatabaseCreation):20    def test_it(self):21        global Parent, Child22        class Parent(Table):23            name = TextField()24            age = IntegerField()25            weight = RealField()26        class Child(Table):27            name = TextField()28            age = IntegerField()29            weight = RealField()30            parent = ForeignKey(Parent)31        assert(Parent.name.type == "TEXT")32        assert(Child.parent.table == Parent)33class TestTableCreation(TestModelDefine):34    def test_it(self):35        super().test_it()36        Parent.create()37        Child.create()38        assert (Parent._get_create_sql() == "CREATE TABLE IF NOT EXISTS parent "39                                            "(id INTEGER PRIMARY KEY, age INTEGER NOT NULL, name TEXT NOT NULL, "40                                            "weight REAL NOT NULL)")41        assert(Child._get_create_sql() == "CREATE TABLE IF NOT EXISTS child (id INTEGER PRIMARY KEY, "42                                          "age INTEGER NOT NULL, "43                                          "name TEXT NOT NULL, parent_id INTEGER, weight REAL NOT NULL, "44                                          "FOREIGN KEY (parent_id) REFERENCES parent(id))")45class TestModelInstanceDefine(TestTableCreation):46    def test_it(self):47        super().test_it()48        global parent1, parent2, child1, child2, child349        parent1 = Parent(name="parent1", age=34, weight=90.1)50        parent2 = Parent(name="parent2", age=41, weight=85.6)51        child1 = Child(name="child1", age=10, weight=35, parent=parent1)52        child2 = Child(name="child2", age=12, weight=36.5, parent=parent2)53        child3 = Child(name="child3", age=8, weight=30, parent=parent2)54        assert (parent1.name == "parent1")55        assert (child1.age == 10)56        assert (child1.parent == parent1)57class TestModelInstanceCreation(TestModelInstanceDefine):58    def test_it(self):59        super().test_it()60        parent1.save()61        parent2.save()62        child1.save()63        child2.save()64        child3.save()65        assert(child3._get_insert_sql() == "INSERT INTO child (name, age, weight, parent_id) VALUES ('child3', 8, 30, 2)")66        assert(parent1.id == 1)67        assert(child3.id == 3)68class TestSelectAll(TestModelInstanceDefine):69    def test_it(self):70        super().test_it()71        global all_parents, all_children72        all_parents = Parent.objects.all()73        all_children = Child.objects.all()74        assert ([x.name for x in all_parents] == ["parent1", "parent2"])75        assert ([x.name for x in all_children] == ["child1", "child2", "child3"])76class TestSelectFilter(TestSelectAll):77    def test_it(self):78        super().test_it()79        par1_child = all_children.filter(Parent.name == 'parent1')80        par2_child = all_children.filter(Parent.name == 'parent2')81        assert ([x.name for x in par1_child] == ["child1"])82        assert ([x.name for x in par2_child] == ["child2", "child3"])83class TestSelectFilter2(TestSelectAll):84    def test_it(self):85        super().test_it()86        all_parents_like = Parent.objects.filter(Parent.name.like('par%') & (Parent.id == 1))87        assert ([x.name for x in all_parents_like] == ["parent1"])88class TestSelectGet(TestSelectAll):89    def test_it(self):90        super().test_it()91        child = Child.objects.get(Child.name == 'child2')92        assert(child.name == "child2")93        assert(child.parent.name == parent2.name)94class TestSelectAllWithResult(TestSelectAll):95    def test_it(self):96        super().test_it()97        all_parents2 = all_parents.all()98        assert ([x.name for x in all_parents2] == [x.name for x in all_parents])99if __name__ == '__main__':...test_str2val.py
Source:test_str2val.py  
...6n_test = 07n_pass = 08n_fail = 09show_all = True     # Show all tests10def test_it(string, exp_val, exp_equal=True, exp_except=False):11    """ Test str2val12    :string: input string13    :exp_val: expected value/type14    :exp_equal: expected equal15    :exp_except: True => exception expected16    :returns: True if OK, else False or SelectError raised17    """18    global n_test, n_pass, n_fail19    n_test += 120    if show_all:21        t_eq_str = f" exp_equal: {exp_equal}" if not exp_equal else ""22        t_except_str = f" exp_except: {exp_except}" if exp_except else ""23        SlTrace.lg(f"{n_test:2d}: test_it {string}, exp_val: {exp_val}{t_eq_str}{t_except_str}")24    try:25        vcvt = str2val(string, exp_val)26        if exp_except:27            n_fail += 128            SlTrace.lg(f"test_it: failed - no exception for: {string} exp_val:{exp_val}")29            return False30        31        if type(vcvt) != type(exp_val):32            n_fail += 133            SlTrace.lg(f"test_it: failed - conversion for: {string} ({vcvt}) != exp_val:{exp_val}")34            return False35        36        if vcvt != exp_val and exp_equal:37            n_fail += 138            SlTrace.lg(f"test_it: failed - {string} ({vcvt}) != {exp_val} when expected equal")39            return False40        41        if vcvt == exp_val and not exp_equal:42            n_fail += 143            SlTrace.lg(f"test_it: failed - {string} ({vcvt}) == {exp_val} when not expected equal")44            return False45            46    except SelectErrorInput:47        if not exp_except:48            n_fail += 149            SlTrace.lg(f"test_it: failed - unexpected exception for: {string} exp_val:{exp_val}")50            return False    51    52    n_pass += 153    SlTrace.lg("Pass")    54    return True55SlTrace.lg("Testing positive cases")56test_it("1", 1)57test_it("True", True)58test_it("2.", 2.)59test_it("abc", "abc")60SlTrace.lg("Testing negative cases")61test_it("12", 1, False)62test_it("False", True, False)63test_it("23.", 2., False)64test_it("abcd", "abc", False)65SlTrace.lg("Testing exception cases")66test_it("12x", 1, exp_except=True)67test_it("Z", True, exp_except=True)68test_it("2x3.", 2, exp_except=True)69SlTrace.lg("\nForce Test Fail")70test_it("1x", 1)71test_it("1", 2)...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!!
