Python scripts in TestComplete

Introduction

Using external libraries

TestComplete has serious problems adapting external libraries.

Things are so bad that right in their documentation they write that they do not guarantee the work of any additional libraries at all, except those that are in their version of Python.

We do not guarantee stable work of your script tests that use third-party Python packages. When you run such tests, you may experience unexpected errors or TestComplete can stop responding.

And what are third-party Pyhon packages? Right, it is everything we install with pip .

So you can write Python scripts, but with additional tools that are hard to imagine a Python developer's work without - all at your own risk.

Everything available out of the box lives in Lib.

Note that there is a 32-bit version

/c/Program Files (x86)/SmartBear/TestComplete 15/Bin/Extensions/Python/Python310/Lib

ls

__future__.py asynchat.py contextlib.py filecmp.py imp.py nturl2path.py pyclbr.py sndhdr.py test/ warnings.py __phello__.foo.py asyncio/ contextvars.py fileinput.py importlib/ numbers.py pydoc.py* socket.py textwrap.py wave.py _aix_support.py asyncore.py copy.py fnmatch.py inspect.py opcode.py pydoc_data/ socketserver.py this.py weakref.py _bootsubprocess.py base64.py* copyreg.py fractions.py io.py operator.py queue.py sqlite3/ threading.py webbrowser.py* _collections_abc.py bdb.py cProfile.py* ftplib.py ipaddress.py optparse.py quopri.py* sre_compile.py timeit.py* wsgiref/ _compat_pickle.py binhex.py crypt.py functools.py json/ os.py random.py sre_constants.py tkinter/ xdrlib.py _compression.py bisect.py csv.py genericpath.py keyword.py pathlib.py re.py sre_parse.py token.py xml/ _markupbase.py bz2.py ctypes/ getopt.py lib2to3/ pdb.py* reprlib.py ssl.py tokenize.py xmlrpc/ _osx_support.py calendar.py curses/ getpass.py linecache.py pickle.py rlcompleter.py stat.py trace.py* zipapp.py _py_abc.py cgi.py* dataclasses.py gettext.py locale.py pickletools.py runpy.py statistics.py traceback.py zipfile.py _pydecimal.py cgitb.py datetime.py glob.py logging/ pipes.py sched.py string.py tracemalloc.py zipimport.py _pyio.py chunk.py dbm/ graphlib.py lzma.py pkgutil.py secrets.py stringprep.py tty.py zoneinfo/ _sitebuiltins.py cmd.py decimal.py gzip.py mailbox.py platform.py* selectors.py struct.py turtle.py _strptime.py code.py difflib.py hashlib.py mailcap.py plistlib.py shelve.py subprocess.py turtledemo/ _threading_local.py codecs.py dis.py heapq.py mimetypes.py poplib.py shlex.py sunau.py types.py _weakrefset.py codeop.py distutils/ hmac.py modulefinder.py posixpath.py shutil.py symtable.py typing.py abc.py collections/ doctest.py html/ msilib/ pprint.py signal.py sysconfig.py unittest/ aifc.py colorsys.py email/ http/ multiprocessing/ profile.py* site.py tabnanny.py* urllib/ antigravity.py compileall.py encodings/ idlelib/ netrc.py pstats.py site-packages/ tarfile.py* uu.py* argparse.py concurrent/ ensurepip/ imaplib.py nntplib.py pty.py smtpd.py* telnetlib.py uuid.py ast.py configparser.py enum.py imghdr.py ntpath.py py_compile.py smtplib.py* tempfile.py venv/

And a 64-bit one

pwd

/c/Program Files (x86)/SmartBear/TestComplete 15/x64/Bin/Extensions/Python/Python310

ls

__future__.py antigravity.py collections/ dis.py gzip.py logging/ pickle.py random.py sqlite3/ textwrap.py venv/ __phello__.foo.py argparse.py colorsys.py distutils/ hashlib.py lzma.py pickletools.py re.py sre_compile.py this.py warnings.py __pycache__/ ast.py compileall.py doctest.py heapq.py mailbox.py pipes.py reprlib.py sre_constants.py threading.py wave.py _aix_support.py asynchat.py concurrent/ email/ hmac.py mailcap.py pkgutil.py rlcompleter.py sre_parse.py timeit.py* weakref.py _bootsubprocess.py asyncio/ configparser.py encodings/ html/ mimetypes.py platform.py* runpy.py ssl.py tkinter/ webbrowser.py* _collections_abc.py asyncore.py contextlib.py ensurepip/ http/ modulefinder.py plistlib.py sched.py stat.py token.py wsgiref/ _compat_pickle.py base64.py* contextvars.py enum.py idlelib/ msilib/ poplib.py secrets.py statistics.py tokenize.py xdrlib.py _compression.py bdb.py copy.py filecmp.py imaplib.py multiprocessing/ posixpath.py selectors.py string.py trace.py* xml/ _markupbase.py binhex.py copyreg.py fileinput.py imghdr.py netrc.py pprint.py shelve.py stringprep.py traceback.py xmlrpc/ _osx_support.py bisect.py cProfile.py* fnmatch.py imp.py nntplib.py profile.py* shlex.py struct.py tracemalloc.py zipapp.py _py_abc.py bz2.py crypt.py fractions.py importlib/ ntpath.py pstats.py shutil.py subprocess.py tty.py zipfile.py _pydecimal.py calendar.py csv.py ftplib.py inspect.py nturl2path.py psycopg2/ signal.py sunau.py turtle.py zipimport.py _pyio.py cgi.py* ctypes/ functools.py io.py numbers.py pty.py site.py symtable.py turtledemo/ zoneinfo/ _sitebuiltins.py cgitb.py curses/ genericpath.py ipaddress.py opcode.py py_compile.py site-packages/ sysconfig.py types.py _strptime.py chunk.py dataclasses.py getopt.py json/ operator.py pyclbr.py smtpd.py* tabnanny.py* typing.py _threading_local.py cmd.py datetime.py getpass.py keyword.py optparse.py pydoc.py* smtplib.py* tarfile.py* unittest/ _weakrefset.py code.py dbm/ gettext.py lib2to3/ os.py pydoc_data/ sndhdr.py telnetlib.py urllib/ abc.py codecs.py decimal.py glob.py linecache.py pathlib.py queue.py socket.py tempfile.py uu.py*

I added the directory psycopg2/ manually.

$ ./python.exe -m pip install --upgrade pip

Requirement already satisfied: pip in c:\program files (x86)\smartbear\testcomplete 15\bin\extensions\python\python310\lib\site-packages (22.3.1) Collecting pip Downloading pip-23.3.1-py3-none-any.whl (2.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 12.2 MB/s eta 0:00:00 Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 22.3.1 Uninstalling pip-22.3.1: Successfully uninstalled pip-22.3.1 WARNING: The scripts pip.exe, pip3.10.exe and pip3.exe are installed in 'C:\Program Files (x86)\SmartBear\TestComplete 15\Bin\Extensions\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed pip-23.3.1

In my Python 3.11 psycopg2 is installed with python -m pip install psycopg2

There psycopg2 imports without any tricks.

import psycopg2 …

python pg_utils.py

TestComplete currently has Python 3.10, so I download the latest version of psycopg2 from their GitHub repository ( link ) as a .zip file

First I unpack it into

C:\Users\Andrei\AppData\Local\Programs\Python\Python310\Lib\site-packages

And then I will do the same in

/c/Program Files (x86)/SmartBear/TestComplete 15/x64/Bin/Extensions/Python/Python310

In Git Bash I change to the directory with the script setup.py

/c/Users/Andrei/AppData/Local/Programs/Python/Python310/python.exe setup.py build
/c/Users/Andrei/AppData/Local/Programs/Python/Python310/python.exe setup.py install

And then on top of that I install psycopg2-binary

/c/Users/Andrei/AppData/Local/Programs/Python/Python310/python.exe -m pip install psycopg2-binary

from os import sys psycopg2_location = "C:\Users\Andrei\AppData\Local\Programs\Python\Python310\Lib\site-packages" sys.path.insert(0, psycopg2_location) import psycopg2 …

/c/Users/Andrei/AppData/Local/Programs/Python/Python310/python.exe pg_utils.py

This method works. I do the same but in the TestComplete directory

from os import sys psycopg2_location = "psycopg2_location = "C:\Program Files (x86)\SmartBear\TestComplete 15\Bin\Extensions\Python\Python310\Lib\site-packages" sys.path.insert(0, psycopg2_location) import psycopg2 …

/c/Program\ Files\ \(x86\)/SmartBear/TestComplete\ 15/Bin/Extensions/Python/Python310/python.exe pg_utils.py

To read from the Postgres database, I had to do manipulations with the system path .

Read more about connecting to Postgres from Python in the article Python + Postgres

from os import sys mode = "py" # Normal Python: system or from venv mode = "tc_py" # TestComplete native Python mode = "tc" # TestComplete GUI if mode == "tc": print = Log.Message if mode in ["tc", "tc_py"]: tc_py_path = "C:\Program Files (x86)\SmartBear\TestComplete 15\x64\Bin\Extensions\Python\Python310" psycopg2_path = tc_py_path + "\Lib\site-packages" print(f"original sys.path: {sys.path}") typing_extension_path = tc_py_path + "\lib\site-packages\typing_extensions-4.8.0-py3.10.egg" tz_data_path = tc_py_path + "\lib\site-packages\tzdata-2023.3-py3.10.egg" zip_path = tc_py_path + "\python310.zip" # sys.path.insert(0, psycopg2_path) # sys.path.insert(0, typing_extension_path) # sys.path.insert(0, tz_data_path) # sys.path.insert(0, zip_path) sys.path = [ psycopg2_path, 'C:\Tests\TestComplete\lib\postgres', zip_path, 'C:\Program Files (x86)\SmartBear\TestComplete 15\x64\Bin\Extensions\Python\Python310\DLLs', 'C:\Program Files (x86)\SmartBear\TestComplete 15\x64\Bin\Extensions\Python\Python310\lib', tc_py_path, tz_data_path, typing_extension_path ] else: print("Executing outside of TestComplete") # psycopg2_path = "C:\Users\" + os.getlogin() + "\AppData\Local\Programs\Python\Python310\Lib\site-packages" # print(psycopg2_path) print(f"sys.prefix: {sys.prefix}") print(f"sys.path: {sys.path}") import psycopg2 from config import credentials def connect(): """ Connect to the PostgreSQL database server """ print(f"connect: {'':-^140}") conn = None try: # read connection parameters params = credentials() print(params) # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.cursor() # execute a statement # print('PostgreSQL database version:') # cur.execute('SELECT version()') # display the PostgreSQL database server version # db_version = cur.fetchone() # print(db_version) return cur except (Exception, psycopg2.DatabaseError) as error: print(f"Connection to DB failed with error: {error}") def main(): cur = connect() result = query(cur) cur = result[0] databases = result[1] print(f"databases: {databases}") db_list = [db[0] for db in databases] # for db in databases: # print(db) # print(type(db)) # db_list.append(db[0]) print(db_list) disconnect(cur) def query(cur): cur.execute("SELECT datname FROM pg_catalog.pg_database") databases = cur.fetchall() print(f"type(databases): {type(databases)}") print(f"query() databases: {databases}") result = (cur, databases) return result def disconnect(cur): # close the communication with the PostgreSQL print("closing connection to PostgreSQL") cur.close() def get_list_of_databases(): cur = connect() cur.execute("SELECT datname FROM pg_catalog.pg_database") databases = cur.fetchall() db_list = [db[0] for db in databases] cur.close() return db_list if __name__ == '__main__': print(get_list_of_databases())

Article author: Andrei Olegovich