Forum Discussion
In JavaScript, I've created a Singleton Class which gets instantiated once, and is called in every test. It reads a configuration file i.e. Storages.INI method, and sets up appropriate parameters, variables etc. While the scripts are running, only one instance is created, and if I create a new instance of the singleton class, the same object is returned.
The same can be applied in Python, see The Singleton Pattern as an example
- mfoster71119 days agoRegular Contributor
I do something similar in Python. The problem is, Python retains the singleton between test items. If I run 10 test items, the singleton only gets created once. This is normally how I want python to work.
But, I have a specific case where I need to reset some values but only when running a new test item.
- Hassan_Ballan19 days ago
Champion Level 3
You could use TestComplete Variables, but that just tracks state โ it doesnโt solve the real issue, which is that Python persists for the entire run in TestComplete.
A cleaner approach is to reset your singleton at the start of each Test Item using a project event.
Do this:
- Go to Project โ Events
- Add an OnStartTest handler
- Reset your class there
Example:
def GeneralEvents_OnStartTest(Sender): MySingleton.reset()And in your class:
class MySingleton: _instance = None @classmethod def reset(cls): cls._instance = NoneSince OnStartTest fires for every Test Item, this guarantees your setup runs once per Test Item without changing how the class is used elsewhere.
๐ค AI-assisted response
๐ Found it helpful? Click Like
โ Issue resolved? Click Mark as Solution- mfoster71119 days agoRegular Contributor
This works. I was thinking there would be a more Python specific solution but this is really a TestComplete issue and TestComplete solution.