Python - Tips

From XennisWiki
Jump to: navigation, search

Basics

argparse

Further information: argparse

def main( sourceDir, testDate ):
  # ...

def parse_args():
  parser = argparse.ArgumentParser(description='''Erstellt einen Bericht.''')
  parser.add_argument('sourceDir', help='Verzeichnis des Tests')
  parser.add_argument('testDate', help='Datum des Tests')
  return parser.parse_args()

if __name__ == "__main__":
  args = parse_args()
  main( args.sourceDir, args.testDate )

DateTime

class DateTimeAction(argparse.Action):

    def __call__(self, parser, namespace, values, option_string=None):
        try:
            date = datetime.strptime(date_string, format='%Y-%m-%dT%H')
            setattr(namespace, self.dest, date)
        except ValueError:
            raise argparse.ArgumentTypeError('Not a valid date: {0}.'.format(values))

argcomplete

Further information: argcomplete

As addition to the argparse example

# The following line is required in the head of the file for the module argcomplete
# PYTHON_ARGCOMPLETE_OK
import argcomplete
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('sourceDir', help='Verzeichnis des Tests')

    argcomplete.autocomplete(parser)
    return parser.parse_args()

Ignore future warnings

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

Connect to MySQL database

import mysql.connector

db = mysql.connector.connect(
    db='NAME',
    host='HOST',
    user='USER',
    passwd='PASSWORD'
)
cursor = db.cursor()
cursor.execute("SELECT COUNT( * ) FROM my_table")
result = cursor.fetchone()
print(result)

MD5 hash

import hashlib
hashlib.md5('some-string'.encode('utf-8')).hexdigest()

Tests

Capture logs during unit tests

# from testfixtures import LogCapture

def test_my_func(self):
    with LogCapture(level=logging.ERROR) as lc:
        my_func()
        lc.check('root', 'ERROR', 'Example log message')

Caputure system exit

def test_my_func(self):
    with self.assertRaises(SystemExit) as system_exit:
        my_func()
    self.assertEqual(system_exit.exception.code, 2)

Capture standard out

import StringIO
import contextlib
import sys

@contextlib.contextmanager
def captured_output():
    new_out, new_err = StringIO.StringIO(), StringIO.StringIO()
    old_out, old_err = sys.stdout, sys.stderr
    try:
        sys.stdout, sys.stderr = new_out, new_err
        yield sys.stdout, sys.stderr
    finally:
        sys.stdout, sys.stderr = old_out, old_err

def test_my_func(self):
    with captured_output() as (out, err):
        foo()
    output = out.getvalue().strip()
    self.assertEqual(output, 'example')

Test exception raise

self.assertRaises(ValueError, my_function, "first argument", "second argument")

Set environment variable for a test

from unittest import mock

with mock.patch.dict('os.environ', {'HOST': 'example.org', 'TOKEN': '0123'}):
    some_function()

Test a function that executes a request

import httmock

@httmock.urlmatch(netloc=r'(.*\.)?example\.org$')
def wp_mock(url, request):
    return {
        'status_code': 200,
        'content': 'OK'
    }

with httmock.HTTMock(wp_mock):
    # some action here, where example.org is requested

CI

Run the tets with coverage

coverage run --module unittest discover -p '*_test.py'
coverage report --show-missing

See Pylint for running the linter.

See also