From 0a0ad5199d5fada3b199f55552852556df58e199 Mon Sep 17 00:00:00 2001 From: Florian Fischer Date: Fri, 11 Aug 2023 12:34:46 +0200 Subject: remove global variables using the environment Previously the geldschieberbot module used global variables retrieved from the environment for its configuration. This is not very flexible and can lead to problems when using the module from other python code. Therefore make all configuration Geldschieberbot specific and pass the values to the constructor. If no values are provided fallback to the environment. This change is fully backwards compatible. --- test.py | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) (limited to 'test.py') diff --git a/test.py b/test.py index 71d6d34..c1a5423 100755 --- a/test.py +++ b/test.py @@ -8,6 +8,8 @@ from string import Template import subprocess import unittest +from geldschieberbot import Geldschieberbot, GeldschieberbotJSONEncoder + alice, bob, charlie = "alice", "bob", "charlie" num = {alice: "+49123456", bob: "+49654321", charlie: "+49615243"} os.environ["GSB_GROUP_ID"] = "test" @@ -96,11 +98,19 @@ def reset_state_string(string): json.dump(json.loads(string), f) -def compare_state(comp_state): - with open(comp_state, "r", encoding='utf-8') as csf, \ - open(os.environ["GSB_STATE_FILE"], "r", encoding='utf-8') as sf: +def compare_state(expected_state_path, + state=None, + state_path=os.environ["GSB_STATE_FILE"]) -> bool: + s = '' + if state is None: + with open(state_path, "r", encoding='utf-8') as sf: + s = sf.read() + else: + s = json.dumps(state, cls=GeldschieberbotJSONEncoder) + + with open(expected_state_path, "r", encoding='utf-8') as csf: cs = csf.read() - s = sf.read() + return cs == s @@ -1375,7 +1385,27 @@ class TestConvertState(unittest.TestCase): res = run_bot(self, num[alice], "!thanks") self.assertEqual( res.stdout, - f"You are welcome. It is a pleasure to work with you, {num['alice']}.") + f"You are welcome. It is a pleasure to work with you, {num['alice']}." + ) + + +class TestStateLoadStore(unittest.TestCase): + + def test_default_init(self): + bot = Geldschieberbot() + self.assertTrue( + compare_state(os.environ['GSB_STATE_FILE'], state=bot.state)) + + def test_explicit_init(self): + sp = "test/state_3users.json" + bot = Geldschieberbot(sp) + self.assertTrue(compare_state(sp, state=bot.state)) + + def test_explicit_load(self): + sp = "test/state_3users.json" + bot = Geldschieberbot() + bot.load_state(sp) + self.assertTrue(compare_state(sp, state=bot.state)) if __name__ == '__main__': -- cgit v1.2.3