pytestDemo

pytest Demo

conftest.py

# -*- coding: utf-8 -*-
import threading
import subprocess
import time
import pytest

def run_with_timeout(timeout = None):
    def _decorator(f):
        def _wrapper(*args, **kwargs):
            def _f(*args, **kwargs):
                try:
                    _result = f(*args, **kwargs)
                except Exception , e:
                    thread._exception = e
                else:
                    thread.result = _result
            thread = threading.Thread(target = _f, args = args, kwargs = kwargs)
            thread.daemon = True
            thread._exception = None

            thread.start()
            thread.join(timeout = timeout)
            if thread.isAlive():
                raise RuntimeError('function *%s* exceeded configured time out of %ss' %(f.__name__, timeout))
                assert False
            if thread._exception is None:
                return thread.result
            else:
                raise thread._exception
        _wrapper.__name__ = f.__name__
        return _wrapper
    return _decorator
def pytest_report_header(config):
    return ["测试!"]

#def pytest_runtest_setup(item):
#    #增加初始化处理部分
#    print "Begin to to some test setup operations ..."
#    p = subprocess.Popen("su postgre", stdin= subprocess.PIPE, stdout = subprocess.PIPE, shell = True)
#    (out, err) = p.communicate("/usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l  /usr/local/pgsql/data/logfile start")
#    print out
#    print err
#def pytest_runtest_teardown(item):
#    print "runtest teardown invoked"
#xUnit style tesing

    
    
def pytest_runtest_call(item):
    if hasattr(item.obj, 'timeout'):
        timeout =item.obj.timeout.args[0]
        item.obj = run_with_timeout(timeout)(item.obj)


    

pytestdemo.py

# -*- coding: utf-8 -*-
#!/usr/bin/python
import psycopg2
import os, sys
import subprocess
import pytest

DBSERVERHOST = "10.0.11.226"
DBPORT = 5432
DBNAME = "source"
DBUSER = "postgre"
DBPASSWORD = "postgre"

def setup_module(module):
    print "\nsetup_module invoked, so i will do some prepare ..."
     #增加初始化处理部分
    p = subprocess.Popen("su postgre", stdin= subprocess.PIPE, stdout = subprocess.PIPE, shell = True)
    (out, err) = p.communicate("/usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l  /usr/local/pgsql/data/logfile start")
    print out
    print err
def teardown_module(module):
    print "\nteardown_module invoked, do some clear up..."
def setup_function(function):
    print "\nsetup_function invoked"
def teardown_function(function):
    print "\nteardown_function invoked"
def test_function1():
    """Just a demo"""
    #清理表
    conn = psycopg2.connect(host = DBSERVERHOST, port = DBPORT, database = DBNAME, \
        user = DBUSER, password = DBPASSWORD)
    cur = conn.cursor()
    cur.execute("truncate table t_pri_sample;")
    cur.execute("truncate table t_pri_package;")
    cur.execute("truncate table t_que_bigpack;")
    cur.execute("truncate table t_src_file_sam;")
    cur.execute("truncate table t_src_archive_sam;")
    conn.commit()
    cur.close()
    conn.close()

    #清理队列
    p = subprocess.Popen("curl 'http://10.2.1.50:1218/?name=QPREP_S&opt=reset'", \
            stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
    #print p.stdout.read()
    assert "HTTPSQS_RESET_OK" in p.stdout.read()     

    #清理TC消重库
    p = subprocess.Popen("/home/t02/prep/Sam/Deal/bin/sh reTC.sh", \
            stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
    #准备测试样本包
    p = subprocess.Popen("cp -r /home/test/testSamples/sample1 /home/t02/prep/In_Pri/in" ,\
            shell = True)
    #启动来源入库进程
    p = subprocess.Popen("/home/t02/prep/In_Pri/bin/go.sh", shell = True)
    #检查文件是否已切至bak目录
    pass
@pytest.mark.timeout(5)
def test_timeout():
    """This test *should* fail when process timeout = 1"""
    from time import sleep
    sleep(10)
def test_fail():
    assert False

运行如下命令进行测试
py.test pytesedemo.py

如果要多pytest做一些config,可以增加pytest.ini:

[pytest]
addopts = -v -s -rfsxX

原文地址:https://www.cnblogs.com/Jerryshome/p/2079767.html