Skip to content

Commit

Permalink
fix bugged singleton implementation
Browse files Browse the repository at this point in the history
Signed-off-by: Maciej Obuchowski <[email protected]>
  • Loading branch information
mobuchowski committed Jun 29, 2023
1 parent 2a55590 commit 9487fbc
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions tests/utils/test_singleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,43 @@ class A(metaclass=Singleton):
pass


class Counter(metaclass=Singleton):
"""Singleton class that counts how much __init__ and count was called."""

counter = 0

def __init__(self):
self.counter += 1

def count(self):
self.counter += 1


def test_singleton_refers_to_same_instance():
a, b = A(), A()
assert a == b
assert a is b


def test_singleton_out_of_context_does_refer_to_same_instance():
def test_singleton_after_out_of_context_does_refer_to_same_instance():
# check if setting something on singleton is preserved after instance goes out of context
def x():
a = A()
a.a = "a"

x()
b = A()
assert b.a == "a"


def test_singleton_does_not_call_init_second_time():
# first creation of Counter, check if __init__ is called
c = Counter()
assert c.counter == 1

# check if "new instance" calls __init__ - it shouldn't
d = Counter()
assert c.counter == 1

# check if incrementing "new instance" increments counter on previous one
d.count()
assert c.counter == 2

0 comments on commit 9487fbc

Please sign in to comment.