Browse Source

TestRun new parameter executeDirect=True and Unit-Tests

bernhardbuhl 4 years ago
parent
commit
c0ec919ae0

+ 34 - 26
baangt/base/TestRun/TestRun.py

@@ -37,50 +37,57 @@ class TestRun:
     """
 
     def __init__(self, testRunName, globalSettingsFileNameAndPath=None,
-                 testRunDict=None, uuid=uuid4()):  # -- API support: testRunDict --
+                 testRunDict=None, uuid=uuid4(), executeDirect=True):  # -- API support: testRunDict --
         """
         @param testRunName: The name of the TestRun to be executed.
         @param globalSettingsFileNameAndPath: from where to read the <globals>.json
         """
-        logger.info('init Testrun, id is {}'.format(id(self)))
 
+        # Take over importing parameters:
+        self.uuid = uuid
+        logger.info(f'Init Testrun, uuid is {self.uuid}')
+        self.testRunDict = testRunDict
+        self.globalSettingsFileNameAndPath = globalSettingsFileNameAndPath
+        self.testRunName, self.testRunFileName = \
+            self._sanitizeTestRunNameAndFileName(testRunName)
+
+        # Initialize everything else
         self.apiInstance = None
         self.testType = None
         self.networkInfo = None
+        self.results = None
+        self.browserFactory = None
         self.kwargs = {}
         self.dataRecords = {}
-        self.globalSettingsFileNameAndPath = globalSettingsFileNameAndPath
         self.globalSettings = {}
         self.managedPaths = ManagedPaths()
         self.classesForObjects = ClassesForObjects()         # Dynamically loaded classes
-
-        # -- API support --
-        # results
-        self.results = None
-        self.testRunDict = testRunDict
-        self.uuid = uuid
-        # -- END of API support
-
+        self.timing = Timing()
+        self.testRunUtils = TestRunUtils()
+        self.testCasesEndDateTimes_1D = []                   # refer to single execution
+        self.testCasesEndDateTimes_2D = [[]]                 # refer to parallel execution
         # New way to export additional Tabs to Excel
         # If you want to export additional data, place a Dict with Tabname + Datafields in additionalExportTabs
         # from anywhere within your custom code base.
         self.additionalExportTabs = {}
 
-        self.testRunName, self.testRunFileName = \
-            self._sanitizeTestRunNameAndFileName(testRunName)
-        self.timing = Timing()
-        self.timing.takeTime(GC.TIMING_TESTRUN)  # Initialize Testrun Duration
-        self.testRunUtils = TestRunUtils()
-        self._initTestRun()  # Loads the globals*.json file
+        # Initialize other values
+        self.timing.takeTime(GC.TIMING_TESTRUN)               # Initialize Testrun Duration
+
+        # Usually the Testrun is called without the parameter executeDirect, meaning it default to "Execute"
+        # during Unit-Tests we don't want this behaviour:
+        if executeDirect:
+            self.executeTestRun()
+
+    def executeTestRun(self):
+        self._initTestRunSettingsFromFile()  # Loads the globals*.json file
 
-        self.testCasesEndDateTimes_1D = []  # refer to single execution
-        self.testCasesEndDateTimes_2D = [[]]  # refer to parallel execution
         self._loadJSONTestRunDefinitions()
         self._loadExcelTestRunDefinitions()
 
         self.browserFactory = BrowserFactory(self)
 
-        self.executeTestRun()
+        self.executeTestSequence()
         self.tearDown()
 
     def append1DTestCaseEndDateTimes(self, dt):
@@ -165,7 +172,7 @@ class TestRun:
         logger.debug(f"Received new result for Testrecord {recordNumber}")
         self.dataRecords[recordNumber] = dataRecordResult
 
-    def executeTestRun(self):
+    def executeTestSequence(self):
         """
         Start TestcaseSequence
 
@@ -238,9 +245,9 @@ class TestRun:
 
         self.kwargs = kwargs
 
-    def _initTestRun(self):
-        self.loadJSONGlobals()
-
+    def _initTestRunSettingsFromFile(self):
+        self.__loadJSONGlobals()
+        self.__sanitizeGlobalsValues()
         self.__setPathsIfNotPredefined()
 
     def __setPathsIfNotPredefined(self):
@@ -262,10 +269,11 @@ class TestRun:
         else:
             self.managedPaths.getOrSetRootPath(path=self.globalSettings.get(GC.PATH_ROOT))
 
-    def loadJSONGlobals(self):
+    def __loadJSONGlobals(self):
         if self.globalSettingsFileNameAndPath:
             self.globalSettings = utils.openJson(self.globalSettingsFileNameAndPath)
 
+    def __sanitizeGlobalsValues(self):
         # Support for new dataClass to load different Classes
         for key, value in self.globalSettings.items():
             if "CL." in key:
@@ -273,7 +281,7 @@ class TestRun:
 
             # Change boolean strings into boolean values.
             if isinstance(value, str):
-                if value.lower() in ("false", "true", "no"):
+                if value.lower() in ("false", "true", "no", "x"):
                     self.globalSettings[key] = utils.anyting2Boolean(value)
 
             if isinstance(value, dict):

+ 1 - 1
baangt/base/TestRun/hookImpls.py

@@ -35,7 +35,7 @@ class TestRunHookImpl(object):
 
     @baangt.hook_impl
     def testRun_executeTestRun(self, testRunObject):
-        return testRunObject.executeTestRun()
+        return testRunObject.executeTestSequence()
 
     @baangt.hook_impl
     def testRun_executeDictSequenceOfClasses(self, testRunObject, dictSequenceOfClasses, counterName, **kwargs):

+ 21 - 0
tests/jsons/globalsFullExample.json

@@ -0,0 +1,21 @@
+{
+    "TC.Lines": "",
+    "TC.dontCloseBrowser": "False",
+    "TC.slowExecution": "False",
+    "TC.NetworkInfo": "X",
+    "TX.DEBUG": "True",
+    "TC.Browser": "FF",
+    "TC.BrowserAttributes": "{'HEADLESS':'True'}",
+    "TC.ParallelRuns": "",
+    "TC.ExportAllFields": "False",
+    "TC.Stage": "other",
+    "TC.Release": "",
+    "TC.RestartBrowser": "False",
+    "TC.UseRotatingProxies": "False",
+    "TC.ReReadProxies": "False",
+    "CL.browserFactory": "zzbaangt.base.BrowserFactory.BrowserFactory",
+    "CL.browserHandling": "baangt.base.BrowserHandling.BrowserHandling.BrowserDriver",
+    "CL.testCaseSequenceMaster": "baangt.TestCaseSequenceMaster.TestCaseSequenceMaster",
+    "TC.TestStepClass": "",
+    "TC.TestDataFileName": ""
+}

+ 10 - 0
tests/jsons/globals_headless2.json

@@ -0,0 +1,10 @@
+{
+    "exportFilesBasePath": "",
+    "TC.Stage": "Test",
+    "TC.Lines": "",
+    "TC.dontCloseBrowser": "True",
+    "TC.BrowserAttributes": "{'HEADLESS': 'True'}",
+    "TC.slowExecution": "True",
+    "TC.NetworkInfo": "True",
+    "TX.DEBUG": "True"
+}

+ 3 - 3
tests/test_testrun.py

@@ -6,9 +6,7 @@ def testrun_obj():
         which will be used by other test methods
     """
     from baangt.base.TestRun.TestRun import TestRun
-    with pytest.raises(Exception) as e:
-        return TestRun("SimpleTheInternet.xlsx","globals.json")
-
+    return TestRun("SimpleTheInternet.xlsx","globals.json", executeDirect=False)
 
 
 def test_filenotfound():
@@ -16,6 +14,7 @@ def test_filenotfound():
     with pytest.raises(Exception) as e:
         TestRun("SimpleTheInternet.xlsx","global.json")
 
+
 def test_objectreturned(testrun_obj):
     """ Returns number of successful and number of error test cases of
          the current test run
@@ -23,6 +22,7 @@ def test_objectreturned(testrun_obj):
     from baangt.base.TestRun.TestRun import TestRun
     assert TestRun.__instancecheck__(testrun_obj)
 
+
 def test_checkattribute(testrun_obj):
     """ check if has attribute """
     assert hasattr(testrun_obj, "getSuccessAndError")

+ 52 - 12
tests/test_testrun_jsonimport.py

@@ -1,12 +1,52 @@
-# import pytest
-# import os
-# from pathlib import Path
-# from baangt.base.TestRun.TestRun import TestRun
-#
-#
-# def test_with_globalsHeadless():
-#     lTestRun = TestRun(str(Path(os.getcwd()).parent.joinpath("examples").joinpath("SimpleTheInternet.xlsx")),
-#                        globalSettingsFileNameAndPath=str(Path(os.getcwd()).joinpath("jsons").joinpath("globals_headless.json")))
-#
-#     assert lTestRun.globalSettings["TC.BrowserAttributes"]
-#     assert isinstance(lTestRun.globalSettings["TC.BrowserAttributes"], dict)
+import pytest
+import os
+from pathlib import Path
+from baangt.base.TestRun.TestRun import TestRun
+
+
+@pytest.fixture
+def testrun_obj():
+    """ This function return instance of TestRun object
+        which will be used by other test methods
+    """
+    from baangt.base.TestRun.TestRun import TestRun
+    return TestRun("SimpleTheInternet.xlsx", "globals.json", executeDirect=False)
+
+
+def test_with_globalsHeadless(testrun_obj):
+    lTestRun = TestRun("SimpleTheInternet.xlsx",
+                       globalSettingsFileNameAndPath= \
+                           Path(os.getcwd()).joinpath("jsons").joinpath("globals_headless.json"),
+                       executeDirect=False)
+    lTestRun._initTestRunSettingsFromFile()
+
+    assert lTestRun.globalSettings["TC.BrowserAttributes"]
+    assert isinstance(lTestRun.globalSettings["TC.BrowserAttributes"], dict)
+
+
+def test_with_globalsHeadlessVersion2(testrun_obj):
+    lTestRun = TestRun("SimpleTheInternet.xlsx",
+                       globalSettingsFileNameAndPath= \
+                           Path(os.getcwd()).joinpath("jsons").joinpath("globals_headless2.json"),
+                       executeDirect=False)
+
+    lTestRun._initTestRunSettingsFromFile()
+
+    assert lTestRun.globalSettings["TC.BrowserAttributes"]
+    assert isinstance(lTestRun.globalSettings["TC.BrowserAttributes"], str)
+
+def tests_with_fullGlobalsFile(testrun_obj):
+    lTestRun = TestRun("SimpleTheInternet.xlsx",
+                       globalSettingsFileNameAndPath= \
+                           Path(os.getcwd()).joinpath("jsons").joinpath("globalsFullExample.json"),
+                       executeDirect=False)
+
+    lTestRun._initTestRunSettingsFromFile()
+
+    assert not lTestRun.globalSettings["TC.Lines"]
+    assert lTestRun.globalSettings["TX.DEBUG"] == True            # Was converted from string "True" to boolean True
+    assert lTestRun.globalSettings["TC.RestartBrowser"] == False  # Was converted from string "False" to boolean False
+    assert lTestRun.globalSettings["TC.NetworkInfo"] == True      # Was converted from string "X" to boolean True
+    assert lTestRun.globalSettings["CL.browserFactory"] == 'zzbaangt.base.BrowserFactory.BrowserFactory'
+    assert lTestRun.classesForObjects.browserFactory == 'zzbaangt.base.BrowserFactory.BrowserFactory'
+