Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

python 3.x - Python3 Unittests, how to prevent private class variables from carrying over between tests

I have two classes, Base and Rectangle. Rectangle inherits from base, and whenever an instance of either is created a private class variable increments (in most conditions) to count the number of instances.

class Base:
    """a class named base"""

    __nb_objects = 0

    def __init__(self, id=None):
        """constructs class"""
        if id is not None:
            self.id = id
        else:
            Base.__nb_objects += 1
            self.id = Base.__nb_objects

from models.base import Base


class Rectangle(Base):
    """a class named Rectangle that inherits from"""

    def __init__(self, width, height, x=0, y=0, id=None):
        """constructs class"""
        super().__init__(id)
        self.__width = width
        self.__height = height
        self.__x = x
        self.__y = y
    #more below, but irrelevant getters and setters for width, height, x, and y

I also have two separate test files that tests my classes. Run individually, both pass however when run together it fails due to the id's from the first test persisting to the next test.

class TestBaseInit(unittest.TestCase):
    """Testing init for base class"""

    def test_base_init(self):
        """adding simple instances"""
        b1 = Base()
        self.assertEqual(b1.id, 1)
        b2 = Base()
        self.assertEqual(b2.id, 2)
        b3 = Base()
        self.assertEqual(b3.id, 3)
        b4 = Base(12)
        self.assertEqual(b4.id, 12)
        b5 = Base()
        self.assertEqual(b5.id, 4)

import unittest
from models.rectangle import Rectangle

class TestRectangleInit(unittest.TestCase):
    """testing init for rectangle class"""

    def test_rectangle_init(self):
        """adding simple rect instances"""
        r1 = Rectangle(10, 2)
        self.assertEqual(r1.id, 1)
        r2 = Rectangle(2, 10)
        self.assertEqual(r2.id, 2)
        r3 = Rectangle(10, 2, 0, 0, 12)
        self.assertEqual(r3.id, 12)

Any tips? I want to make it so the difference tests on the two different files don't interfere with eachother (Somehow ensuring individual tests have their own instance of everything?).

question from:https://stackoverflow.com/questions/65853585/python3-unittests-how-to-prevent-private-class-variables-from-carrying-over-bet

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...