import os
import sys
import importlib.util
import pathlib

ROOT = pathlib.Path(__file__).parent.parent.absolute()
TESTS_FOLDER_NAME = os.path.normpath("/tests")

print("\nSearching for tests at the path: "+ str(ROOT))

count = 0
resultCodeList = []
for (dirname, dirs, files) in os.walk(ROOT):

    #I assume all the tests are placed in a folder named "tests"
    if (TESTS_FOLDER_NAME in str(dirname)) \
        and not(f"{TESTS_FOLDER_NAME}{os.path.normpath('/')}" in str(dirname)) \
        and not("venv" in str(dirname)):
        try:
            print(f"Executing tests in {dirname}")
            os.chdir(os.path.normpath(dirname))
            # TODO do this during docker image setup
            exit_val = os.system("python3.7 -m pip install -r ../requirements.txt") # install pip dependencies
            exit_val = os.system("python3.7 -m unittest discover") # execute the tests
            resultCodeList.append(exit_val) #once per folder  i.e if 3 tests are in a folder and crash, there will be just one exit val
        except Exception as e:
            print(e)
            continue

firstError = -1
i = 0
while i < len(resultCodeList):
    if resultCodeList[i] != 0:
        # print("\nA test failed with code: "+ str(resultCodeList[i]))
        if (firstError < 0):
            firstError = i
    i += 1

if(firstError<0): #no errors found
    sys.exit(0)
else:
    sys.exit(1) #return code>0