Testing Python with Pytest

Enable Javascript to display Table of Contents.

Example

The dependencies have to be defined in the file requirements.txt:
paramiko
pytest
The file to be tested must be named test_xxx.py to be found by pytest:
#!/usr/bin/env python3
#
# Tests the logs to be in UTC/ISO
#
# Execution:
#
#  $ python3 -m venv venv
#  $ source venv/bin/active
#  $ python3 -m pip install -r requirements.txt
#  $ python3 -m pytest --verbose --capture=no -k mytest
#

import paramiko
import pytest
import sys

def file_exists(sftp, path):
    try:
        sftp.stat(path)
        return True
    except FileNotFoundError:
        return False


@pytest.fixture
def setup_environment():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('jupiter007', username='theuser', password='mygoodpassword')
    sftp = ssh.open_sftp()
    sftp.chdir('/tmp')
    if not file_exists(sftp, 'check_utc_iso_logs'):
        sftp.mkdir('check_utc_iso_logs')
    sftp.chdir('check_utc_iso_logs')
    sftp.put('exclude.csv', 'exclude.csv')
    yield ssh
    sftp.close()
    ssh.close()

def test_mytest(setup_environment):
    print('hallo')
    ssh = setup_environment
    stdin, stdout, stderr = ssh.exec_command('dpkg -l')
    for line in stdout:
        print(' | ' + line.strip('\n'))
    print('welt')

if __name__ == '__main__':
    sys.exit(pytest.main(["--capture=no", "--verbose"]))