[svn r57320] remove test, misc, doc, io, and code directories
that are to come from the event branch with the next commit. --HG-- branch : trunk
This commit is contained in:
@@ -1 +0,0 @@
|
||||
#
|
||||
@@ -1,12 +0,0 @@
|
||||
|
||||
def f1():
|
||||
f2()
|
||||
|
||||
def f2():
|
||||
pass
|
||||
|
||||
def g1():
|
||||
g2()
|
||||
|
||||
def g2():
|
||||
raise ValueError()
|
||||
@@ -1,30 +0,0 @@
|
||||
|
||||
""" some example for running box stuff inside
|
||||
"""
|
||||
|
||||
import sys
|
||||
import py, os
|
||||
|
||||
def boxf1():
|
||||
print "some out"
|
||||
print >>sys.stderr, "some err"
|
||||
return 1
|
||||
|
||||
def boxf2():
|
||||
os.write(1, "someout")
|
||||
os.write(2, "someerr")
|
||||
return 2
|
||||
|
||||
def boxseg():
|
||||
os.kill(os.getpid(), 11)
|
||||
|
||||
def boxhuge():
|
||||
os.write(1, " " * 10000)
|
||||
os.write(2, " " * 10000)
|
||||
os.write(1, " " * 10000)
|
||||
|
||||
os.write(1, " " * 10000)
|
||||
os.write(2, " " * 10000)
|
||||
os.write(2, " " * 10000)
|
||||
os.write(1, " " * 10000)
|
||||
return 3
|
||||
@@ -1 +0,0 @@
|
||||
#
|
||||
@@ -1 +0,0 @@
|
||||
from package import shared_lib
|
||||
@@ -1 +0,0 @@
|
||||
import shared_lib
|
||||
@@ -1,3 +0,0 @@
|
||||
"""
|
||||
Just a dummy module
|
||||
"""
|
||||
@@ -1,52 +0,0 @@
|
||||
import sys
|
||||
import os
|
||||
|
||||
def setup_module(mod=None):
|
||||
if mod is None:
|
||||
f = __file__
|
||||
else:
|
||||
f = mod.__file__
|
||||
sys.path.append(os.path.dirname(os.path.dirname(f)))
|
||||
|
||||
def teardown_module(mod=None):
|
||||
if mod is None:
|
||||
f = __file__
|
||||
else:
|
||||
f = mod.__file__
|
||||
sys.path.remove(os.path.dirname(os.path.dirname(f)))
|
||||
|
||||
def test_import():
|
||||
global shared_lib, module_that_imports_shared_lib
|
||||
import shared_lib
|
||||
from package import shared_lib as shared_lib2
|
||||
import module_that_imports_shared_lib
|
||||
import absolute_import_shared_lib
|
||||
all_modules = [
|
||||
('shared_lib', shared_lib),
|
||||
('shared_lib2', shared_lib2),
|
||||
('module_that_imports_shared_lib',
|
||||
module_that_imports_shared_lib.shared_lib),
|
||||
('absolute_import_shared_lib',
|
||||
absolute_import_shared_lib.shared_lib),
|
||||
]
|
||||
bad_matches = []
|
||||
while all_modules:
|
||||
name1, mod1 = all_modules[0]
|
||||
all_modules = all_modules[1:]
|
||||
for name2, mod2 in all_modules:
|
||||
if mod1 is not mod2:
|
||||
bad_matches.append((name1, mod1, name2, mod2))
|
||||
for name1, mod1, name2, mod2 in bad_matches:
|
||||
print "These modules should be identical:"
|
||||
print " %s:" % name1
|
||||
print " ", mod1
|
||||
print " %s:" % name2
|
||||
print " ", mod2
|
||||
print
|
||||
if bad_matches:
|
||||
assert False
|
||||
|
||||
if __name__ == "__main__":
|
||||
setup_module()
|
||||
test_import
|
||||
teardown_module()
|
||||
@@ -1,123 +0,0 @@
|
||||
import py
|
||||
|
||||
def setup_module(mod):
|
||||
mod.datadir = setupdatadir()
|
||||
mod.tmpdir = py.test.ensuretemp(mod.__name__)
|
||||
|
||||
def setupdatadir():
|
||||
datadir = py.test.ensuretemp("datadir")
|
||||
names = [x.basename for x in datadir.listdir()]
|
||||
for name, content in namecontent:
|
||||
if name not in names:
|
||||
datadir.join(name).write(content)
|
||||
return datadir
|
||||
|
||||
namecontent = [
|
||||
('syntax_error.py', "this is really not python\n"),
|
||||
|
||||
('disabled_module.py', py.code.Source('''
|
||||
disabled = True
|
||||
|
||||
def setup_module(mod):
|
||||
raise ValueError
|
||||
|
||||
class TestClassOne:
|
||||
def test_func(self):
|
||||
raise ValueError
|
||||
|
||||
class TestClassTwo:
|
||||
def setup_class(cls):
|
||||
raise ValueError
|
||||
def test_func(self):
|
||||
raise ValueError
|
||||
''')),
|
||||
|
||||
('brokenrepr.py', py.code.Source('''
|
||||
|
||||
import py
|
||||
|
||||
class BrokenRepr1:
|
||||
"""A broken class with lots of broken methods. Let's try to make the test framework
|
||||
immune to these."""
|
||||
foo=0
|
||||
def __repr__(self):
|
||||
raise Exception("Ha Ha fooled you, I'm a broken repr().")
|
||||
|
||||
class BrokenRepr2:
|
||||
"""A broken class with lots of broken methods. Let's try to make the test framework
|
||||
immune to these."""
|
||||
foo=0
|
||||
def __repr__(self):
|
||||
raise "Ha Ha fooled you, I'm a broken repr()."
|
||||
|
||||
|
||||
class TestBrokenClass:
|
||||
|
||||
def test_explicit_bad_repr(self):
|
||||
t = BrokenRepr1()
|
||||
py.test.raises(Exception, 'repr(t)')
|
||||
|
||||
def test_implicit_bad_repr1(self):
|
||||
t = BrokenRepr1()
|
||||
assert t.foo == 1
|
||||
|
||||
def test_implicit_bad_repr2(self):
|
||||
t = BrokenRepr2()
|
||||
assert t.foo == 1
|
||||
''')),
|
||||
|
||||
('failingimport.py', py.code.Source('''
|
||||
|
||||
import gruetzelmuetzel
|
||||
|
||||
''')),
|
||||
|
||||
('filetest.py', py.code.Source('''
|
||||
def test_one():
|
||||
assert 42 == 43
|
||||
|
||||
class TestClass(object):
|
||||
def test_method_one(self):
|
||||
assert 42 == 43
|
||||
|
||||
''')),
|
||||
('testmore.py', py.code.Source('''
|
||||
def test_one():
|
||||
assert 1
|
||||
|
||||
def test_two():
|
||||
assert 1
|
||||
|
||||
def test_three():
|
||||
assert 1
|
||||
''')),
|
||||
('testevenmore.py', py.code.Source('''
|
||||
def test_one():
|
||||
assert 1
|
||||
|
||||
def test_two():
|
||||
assert 1
|
||||
|
||||
def test_three():
|
||||
assert 1
|
||||
|
||||
def test_four():
|
||||
assert 1
|
||||
''')),
|
||||
|
||||
('testspecial_importerror.py', py.code.Source('''
|
||||
|
||||
import asdasd
|
||||
|
||||
''')),
|
||||
|
||||
('disabled.py', py.code.Source('''
|
||||
class TestDisabled:
|
||||
disabled = True
|
||||
def test_method(self):
|
||||
pass
|
||||
''')),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
|
||||
""" test boxing functionality
|
||||
"""
|
||||
|
||||
import py, sys, os
|
||||
|
||||
if sys.platform == 'win32':
|
||||
py.test.skip("rsession is unsupported on Windows.")
|
||||
|
||||
from py.__.test.box import Box
|
||||
from py.__.test.testing import example2
|
||||
|
||||
def setup_module(mod):
|
||||
tmpdir = py.test.ensuretemp("boxtests")
|
||||
mod.config = py.test.config._reparse([tmpdir])
|
||||
|
||||
def test_basic_boxing():
|
||||
# XXX: because we do not have option transfer
|
||||
## if not hasattr(option, 'nocapture') or not option.nocapture:
|
||||
## py.test.skip("Interacts with pylib i/o skipping which is bad actually")
|
||||
b = Box(example2.boxf1, config=config)
|
||||
b.run()
|
||||
assert b.stdoutrepr == "some out\n"
|
||||
assert b.stderrrepr == "some err\n"
|
||||
assert b.exitstat == 0
|
||||
assert b.signal == 0
|
||||
assert b.retval == 1
|
||||
|
||||
def test_boxing_on_fds():
|
||||
b = Box(example2.boxf2, config=config)
|
||||
b.run()
|
||||
assert b.stdoutrepr == "someout"
|
||||
assert b.stderrrepr == "someerr"
|
||||
assert b.exitstat == 0
|
||||
assert b.signal == 0
|
||||
assert b.retval == 2
|
||||
|
||||
def test_boxing_signal():
|
||||
b = Box(example2.boxseg, config=config)
|
||||
b.run()
|
||||
assert b.retval is None
|
||||
if py.std.sys.version_info < (2,4):
|
||||
py.test.skip("signal detection does not work with python prior 2.4")
|
||||
assert b.signal == 11
|
||||
|
||||
def test_boxing_huge_data():
|
||||
b = Box(example2.boxhuge, config=config)
|
||||
b.run()
|
||||
assert b.stdoutrepr
|
||||
assert b.exitstat == 0
|
||||
assert b.signal == 0
|
||||
assert b.retval == 3
|
||||
|
||||
def test_box_seq():
|
||||
# we run many boxes with huge data, just one after another
|
||||
for i in xrange(100):
|
||||
b = Box(example2.boxhuge, config=config)
|
||||
b.run()
|
||||
assert b.stdoutrepr
|
||||
assert b.exitstat == 0
|
||||
assert b.signal == 0
|
||||
assert b.retval == 3
|
||||
|
||||
def test_box_in_a_box():
|
||||
def boxfun():
|
||||
b = Box(example2.boxf2, config=config)
|
||||
b.run()
|
||||
print b.stdoutrepr
|
||||
print >>sys.stderr, b.stderrrepr
|
||||
return b.retval
|
||||
|
||||
b = Box(boxfun, config=config)
|
||||
b.run()
|
||||
assert b.stdoutrepr == "someout\n"
|
||||
assert b.stderrrepr == "someerr\n"
|
||||
assert b.exitstat == 0
|
||||
assert b.signal == 0
|
||||
assert b.retval == 2
|
||||
|
||||
def test_box_killer():
|
||||
class A:
|
||||
pass
|
||||
info = A()
|
||||
import time
|
||||
|
||||
def box_fun():
|
||||
time.sleep(10) # we don't want to last forever here
|
||||
|
||||
b = Box(box_fun, config=config)
|
||||
par, pid = b.run(continuation=True)
|
||||
os.kill(pid, 15)
|
||||
par(pid)
|
||||
if py.std.sys.version_info < (2,4):
|
||||
py.test.skip("signal detection does not work with python prior 2.4")
|
||||
assert b.signal == 15
|
||||
@@ -1,483 +0,0 @@
|
||||
from __future__ import generators
|
||||
import py
|
||||
from setupdata import setupdatadir
|
||||
from py.__.test.outcome import Skipped, Failed, Passed, Outcome
|
||||
from py.__.test.terminal.out import getout
|
||||
from py.__.test.repevent import ReceivedItemOutcome
|
||||
|
||||
def getpassed(all):
|
||||
outcomes = [i.outcome for i in all if isinstance(i, ReceivedItemOutcome)]
|
||||
l = [i for i in outcomes if i.passed]
|
||||
return l
|
||||
|
||||
def setup_module(mod):
|
||||
mod.datadir = setupdatadir()
|
||||
mod.tmpdir = py.test.ensuretemp('test_collect')
|
||||
|
||||
def test_failing_import_execfile():
|
||||
dest = datadir / 'failingimport.py'
|
||||
col = py.test.collect.Module(dest)
|
||||
py.test.raises(ImportError, col.run)
|
||||
py.test.raises(ImportError, col.run)
|
||||
|
||||
def test_collect_listnames_and_back():
|
||||
col1 = py.test.collect.Directory(datadir.dirpath())
|
||||
col2 = col1.join(datadir.basename)
|
||||
col3 = col2.join('filetest.py')
|
||||
l = col3.listnames()
|
||||
assert len(l) == 3
|
||||
x = col1._getitembynames(l[1:])
|
||||
assert x.name == "filetest.py"
|
||||
x = col1._getitembynames("/".join(l[1:]))
|
||||
assert x.name == "filetest.py"
|
||||
l2 = x.listnames()
|
||||
assert len(l2) == 3
|
||||
|
||||
def test_finds_tests():
|
||||
fn = datadir / 'filetest.py'
|
||||
col = py.test.collect.Module(fn)
|
||||
l = col.run()
|
||||
assert len(l) == 2
|
||||
assert l[0] == 'test_one'
|
||||
assert l[1] == 'TestClass'
|
||||
|
||||
def test_found_certain_testfiles():
|
||||
tmp = py.test.ensuretemp("found_certain_testfiles")
|
||||
tmp.ensure('test_found.py')
|
||||
tmp.ensure('found_test.py')
|
||||
|
||||
colitem = py.test.collect.Directory(tmp)
|
||||
items = list(colitem._tryiter(py.test.collect.Module))
|
||||
assert len(items) == 2
|
||||
items = [item.name for item in items]
|
||||
assert 'test_found.py' in items
|
||||
assert 'found_test.py' in items
|
||||
|
||||
def test_ignored_certain_directories():
|
||||
tmp = py.test.ensuretemp("ignore_certain_directories")
|
||||
tmp.ensure("_darcs", 'test_notfound.py')
|
||||
tmp.ensure("CVS", 'test_notfound.py')
|
||||
tmp.ensure("{arch}", 'test_notfound.py')
|
||||
tmp.ensure(".whatever", 'test_notfound.py')
|
||||
tmp.ensure(".bzr", 'test_notfound.py')
|
||||
tmp.ensure("normal", 'test_found.py')
|
||||
tmp.ensure('test_found.py')
|
||||
|
||||
colitem = py.test.collect.Directory(tmp)
|
||||
items = list(colitem._tryiter(py.test.collect.Module))
|
||||
assert len(items) == 2
|
||||
for item in items:
|
||||
assert item.name == 'test_found.py'
|
||||
|
||||
def test_failing_import_directory():
|
||||
class MyDirectory(py.test.collect.Directory):
|
||||
def filefilter(self, p):
|
||||
return p.check(fnmatch='testspecial*.py')
|
||||
mydir = MyDirectory(datadir)
|
||||
l = mydir.run()
|
||||
assert len(l) == 1
|
||||
item = mydir.join(l[0])
|
||||
assert isinstance(item, py.test.collect.Module)
|
||||
py.test.raises(ImportError, item.run)
|
||||
|
||||
def test_module_file_not_found():
|
||||
fn = datadir.join('nada','no')
|
||||
col = py.test.collect.Module(fn)
|
||||
py.test.raises(py.error.ENOENT, col.run)
|
||||
|
||||
def test_syntax_error_in_module():
|
||||
p = py.test.ensuretemp("syntaxerror1").join('syntax_error.py')
|
||||
p.write("\nthis is really not python\n")
|
||||
modpath = datadir.join('syntax_error.py')
|
||||
col = py.test.collect.Module(modpath)
|
||||
py.test.raises(SyntaxError, col.run)
|
||||
|
||||
def test_disabled_class():
|
||||
col = py.test.collect.Module(datadir.join('disabled.py'))
|
||||
l = col.run()
|
||||
assert len(l) == 1
|
||||
colitem = col.join(l[0])
|
||||
assert isinstance(colitem, py.test.collect.Class)
|
||||
assert not colitem.run()
|
||||
|
||||
def test_disabled_module():
|
||||
col = py.test.collect.Module(datadir.join('disabled_module.py'))
|
||||
l = col.run()
|
||||
assert len(l) == 0
|
||||
|
||||
class Testsomeclass:
|
||||
disabled = True
|
||||
def test_something():
|
||||
raise ValueError
|
||||
|
||||
|
||||
#class TestWithCustomItem:
|
||||
# class Item(py.test.collect.Item):
|
||||
# flag = []
|
||||
# def execute(self, target, *args):
|
||||
# self.flag.append(42)
|
||||
# target(*args)
|
||||
#
|
||||
# def test_hello(self):
|
||||
# assert self.Item.flag == [42]
|
||||
#
|
||||
|
||||
def test_generative_simple():
|
||||
o = tmpdir.ensure('generativetest', dir=1)
|
||||
tfile = o.join('test_generative.py')
|
||||
tfile.write(py.code.Source("""
|
||||
from __future__ import generators # python2.2!
|
||||
def func1(arg, arg2):
|
||||
assert arg == arg2
|
||||
|
||||
def test_gen():
|
||||
yield func1, 17, 3*5
|
||||
yield func1, 42, 6*7
|
||||
|
||||
class TestGenMethods:
|
||||
def test_gen(self):
|
||||
yield func1, 17, 3*5
|
||||
yield func1, 42, 6*7
|
||||
"""))
|
||||
col = py.test.collect.Module(tfile)
|
||||
l = col.run()
|
||||
assert len(l) == 2
|
||||
l = col.multijoin(l)
|
||||
|
||||
generator = l[0]
|
||||
assert isinstance(generator, py.test.collect.Generator)
|
||||
l2 = generator.run()
|
||||
assert len(l2) == 2
|
||||
l2 = generator.multijoin(l2)
|
||||
assert isinstance(l2[0], py.test.collect.Function)
|
||||
assert isinstance(l2[1], py.test.collect.Function)
|
||||
assert l2[0].name == '[0]'
|
||||
assert l2[1].name == '[1]'
|
||||
|
||||
assert l2[0].obj.func_name == 'func1'
|
||||
|
||||
classlist = l[1].run()
|
||||
assert len(classlist) == 1
|
||||
classlist = l[1].multijoin(classlist)
|
||||
cls = classlist[0]
|
||||
generator = cls.join(cls.run()[0])
|
||||
assert isinstance(generator, py.test.collect.Generator)
|
||||
l2 = generator.run()
|
||||
assert len(l2) == 2
|
||||
l2 = generator.multijoin(l2)
|
||||
assert isinstance(l2[0], py.test.collect.Function)
|
||||
assert isinstance(l2[1], py.test.collect.Function)
|
||||
assert l2[0].name == '[0]'
|
||||
assert l2[1].name == '[1]'
|
||||
|
||||
def test_custom_python_collection_from_conftest():
|
||||
o = tmpdir.ensure('customconfigtest', dir=1)
|
||||
o.ensure('conftest.py').write("""if 1:
|
||||
import py
|
||||
class MyFunction(py.test.collect.Function):
|
||||
pass
|
||||
class Directory(py.test.collect.Directory):
|
||||
def filefilter(self, fspath):
|
||||
return fspath.check(basestarts='check_', ext='.py')
|
||||
class myfuncmixin:
|
||||
Function = MyFunction
|
||||
def funcnamefilter(self, name):
|
||||
return name.startswith('check_')
|
||||
|
||||
class Module(myfuncmixin, py.test.collect.Module):
|
||||
def classnamefilter(self, name):
|
||||
return name.startswith('CustomTestClass')
|
||||
class Instance(myfuncmixin, py.test.collect.Instance):
|
||||
pass
|
||||
""")
|
||||
checkfile = o.ensure('somedir', 'check_something.py')
|
||||
checkfile.write("""if 1:
|
||||
def check_func():
|
||||
assert 42 == 42
|
||||
class CustomTestClass:
|
||||
def check_method(self):
|
||||
assert 23 == 23
|
||||
""")
|
||||
|
||||
for x in (o, checkfile, checkfile.dirpath()):
|
||||
config = py.test.config._reparse([x])
|
||||
#print "checking that %s returns custom items" % (x,)
|
||||
col = config._getcollector(x)
|
||||
assert len(list(col._tryiter(py.test.collect.Item))) == 2
|
||||
#assert items[1].__class__.__name__ == 'MyFunction'
|
||||
|
||||
# test that running a session works from the directories
|
||||
old = o.chdir()
|
||||
try:
|
||||
config = py.test.config._reparse([])
|
||||
all = []
|
||||
session = config._getsessionclass()(config)
|
||||
session.main(all.append)
|
||||
l = getpassed(all)
|
||||
assert len(l) == 2
|
||||
finally:
|
||||
old.chdir()
|
||||
|
||||
# test that running the file directly works
|
||||
config = py.test.config._reparse([str(checkfile)])
|
||||
all = []
|
||||
session = config._getsessionclass()(config)
|
||||
session.main(all.append)
|
||||
l = getpassed(all)
|
||||
assert len(l) == 2
|
||||
|
||||
def test_custom_NONpython_collection_from_conftest():
|
||||
o = tmpdir.ensure('customconfigtest_nonpython', dir=1)
|
||||
o.ensure('conftest.py').write("""if 1:
|
||||
import py
|
||||
class CustomItem(py.test.collect.Item):
|
||||
def run(self):
|
||||
pass
|
||||
|
||||
class Directory(py.test.collect.Directory):
|
||||
def filefilter(self, fspath):
|
||||
return fspath.check(basestarts='check_', ext='.txt')
|
||||
def join(self, name):
|
||||
if not name.endswith('.txt'):
|
||||
return super(Directory, self).join(name)
|
||||
p = self.fspath.join(name)
|
||||
if p.check(file=1):
|
||||
return CustomItem(p, parent=self)
|
||||
""")
|
||||
checkfile = o.ensure('somedir', 'moredir', 'check_something.txt')
|
||||
|
||||
for x in (o, checkfile, checkfile.dirpath()):
|
||||
print "checking that %s returns custom items" % (x,)
|
||||
config = py.test.config._reparse([x])
|
||||
col = config._getcollector(x)
|
||||
assert len(list(col._tryiter(py.test.collect.Item))) == 1
|
||||
#assert items[1].__class__.__name__ == 'MyFunction'
|
||||
|
||||
# test that running a session works from the directories
|
||||
old = o.chdir()
|
||||
try:
|
||||
config = py.test.config._reparse([])
|
||||
all = []
|
||||
session = config._getsessionclass()(config)
|
||||
session.main(all.append)
|
||||
l = getpassed(all)
|
||||
assert len(l) == 1
|
||||
finally:
|
||||
old.chdir()
|
||||
|
||||
# test that running the file directly works
|
||||
config = py.test.config._reparse([str(checkfile)])
|
||||
all = []
|
||||
session = config._getsessionclass()(config)
|
||||
session.main(all.append)
|
||||
l = getpassed(all)
|
||||
assert len(l) == 1
|
||||
|
||||
def test_order_of_execution_generator_same_codeline():
|
||||
o = tmpdir.ensure('genorder1', dir=1)
|
||||
o.join("test_order1.py").write(py.code.Source("""
|
||||
def test_generative_order_of_execution():
|
||||
test_list = []
|
||||
expected_list = range(6)
|
||||
|
||||
def list_append(item):
|
||||
test_list.append(item)
|
||||
|
||||
def assert_order_of_execution():
|
||||
print 'expected order', expected_list
|
||||
print 'but got ', test_list
|
||||
assert test_list == expected_list
|
||||
|
||||
for i in expected_list:
|
||||
yield list_append, i
|
||||
yield assert_order_of_execution
|
||||
"""))
|
||||
config = py.test.config._reparse([o])
|
||||
all = []
|
||||
session = config.initsession()
|
||||
session.main(all.append)
|
||||
l = getpassed(all)
|
||||
assert len(l) == 7
|
||||
|
||||
def test_order_of_execution_generator_different_codeline():
|
||||
o = tmpdir.ensure('genorder2', dir=2)
|
||||
o.join("test_genorder2.py").write(py.code.Source("""
|
||||
def test_generative_tests_different_codeline():
|
||||
test_list = []
|
||||
expected_list = range(3)
|
||||
|
||||
def list_append_2():
|
||||
test_list.append(2)
|
||||
|
||||
def list_append_1():
|
||||
test_list.append(1)
|
||||
|
||||
def list_append_0():
|
||||
test_list.append(0)
|
||||
|
||||
def assert_order_of_execution():
|
||||
print 'expected order', expected_list
|
||||
print 'but got ', test_list
|
||||
assert test_list == expected_list
|
||||
|
||||
yield list_append_0
|
||||
yield list_append_1
|
||||
yield list_append_2
|
||||
yield assert_order_of_execution
|
||||
"""))
|
||||
config = py.test.config._reparse([o])
|
||||
all = []
|
||||
session = config.initsession()
|
||||
session.main(all.append)
|
||||
l = getpassed(all)
|
||||
assert len(l) == 4
|
||||
|
||||
|
||||
|
||||
def test_documentation_virtual_collector_interaction():
|
||||
rootdir = py.path.local(py.__file__).dirpath("doc")
|
||||
# HACK
|
||||
from py.__.doc import conftest as conf
|
||||
old = conf.option.forcegen
|
||||
try:
|
||||
conf.option.forcegen = 1
|
||||
col = py.test.collect.Directory(rootdir)
|
||||
x = list(col._tryiter(yieldtype=py.test.collect.Function))
|
||||
finally:
|
||||
conf.option.forcegen = old
|
||||
|
||||
|
||||
def test__tryiter_ignores_skips():
|
||||
tmp = py.test.ensuretemp("_tryiterskip")
|
||||
tmp.ensure("subdir", "conftest.py").write(py.code.Source("""
|
||||
import py
|
||||
class Directory(py.test.collect.Directory):
|
||||
def run(self):
|
||||
py.test.skip("intentional")
|
||||
"""))
|
||||
col = py.test.collect.Directory(tmp)
|
||||
try:
|
||||
list(col._tryiter())
|
||||
except KeyboardInterrupt:
|
||||
raise
|
||||
except:
|
||||
exc = py.code.ExceptionInfo()
|
||||
py.test.fail("should not have raised: %s" %(exc,))
|
||||
|
||||
|
||||
def test__tryiter_ignores_failing_collectors():
|
||||
tmp = py.test.ensuretemp("_tryiterfailing")
|
||||
tmp.ensure("subdir", "conftest.py").write(py.code.Source("""
|
||||
bla bla bla
|
||||
"""))
|
||||
col = py.test.collect.Directory(tmp)
|
||||
try:
|
||||
list(col._tryiter())
|
||||
except KeyboardInterrupt:
|
||||
raise
|
||||
except:
|
||||
exc = py.code.ExceptionInfo()
|
||||
py.test.fail("should not have raised: %s" %(exc,))
|
||||
|
||||
l = []
|
||||
|
||||
def test_tryiter_handles_keyboardinterrupt():
|
||||
tmp = py.test.ensuretemp("tryiterkeyboard")
|
||||
tmp.ensure("subdir", "conftest.py").write(py.code.Source("""
|
||||
raise KeyboardInterrupt()
|
||||
"""))
|
||||
col = py.test.collect.Directory(tmp)
|
||||
py.test.raises(KeyboardInterrupt, list, col._tryiter())
|
||||
|
||||
def test_check_random_inequality():
|
||||
tmp = py.test.ensuretemp("ineq")
|
||||
tmp.ensure("test_x.py").write(py.code.Source("""def test_one():
|
||||
pass
|
||||
"""))
|
||||
col = py.test.collect.Directory(tmp)
|
||||
fn = col._tryiter().next()
|
||||
assert fn != 3
|
||||
assert fn != col
|
||||
assert fn != [1,2,3]
|
||||
assert [1,2,3] != fn
|
||||
assert col != fn
|
||||
|
||||
def test_check_generator_collect_problems():
|
||||
tmp = py.test.ensuretemp("gener_coll")
|
||||
tmp.ensure("test_one.py").write(py.code.Source("""
|
||||
def setup_module(mod):
|
||||
mod.x = [1,2,3]
|
||||
|
||||
def check(zzz):
|
||||
assert zzz
|
||||
|
||||
def test_one():
|
||||
for i in x:
|
||||
yield check, i
|
||||
"""))
|
||||
tmp.ensure("__init__.py")
|
||||
col = py.test.collect.Module(tmp.join("test_one.py"))
|
||||
assert len(col.join('test_one').run()) == 3
|
||||
|
||||
def test_generator_setup_invoked_twice():
|
||||
py.test.skip("Test for generators not invoking setup, needs thinking")
|
||||
tmp = py.test.ensuretemp("generator_setup_invoke")
|
||||
tmp.ensure("test_one.py").write(py.code.Source("""
|
||||
def setup_module(mod):
|
||||
mod.x = []
|
||||
|
||||
def setup_function(fun):
|
||||
x.append(1)
|
||||
|
||||
def test_one():
|
||||
yield lambda: None
|
||||
"""))
|
||||
tmp.ensure("__init__.py")
|
||||
col = py.test.collect.Module(tmp.join("test_one.py"))
|
||||
l = list(col._tryiter())
|
||||
assert not hasattr(col.obj, 'x')
|
||||
|
||||
def test_check_collect_hashes():
|
||||
tmp = py.test.ensuretemp("check_collect_hashes")
|
||||
tmp.ensure("test_one.py").write(py.code.Source("""
|
||||
def test_1():
|
||||
pass
|
||||
|
||||
def test_2():
|
||||
pass
|
||||
"""))
|
||||
tmp.ensure("test_two.py").write(py.code.Source("""
|
||||
def test_1():
|
||||
pass
|
||||
|
||||
def test_2():
|
||||
pass
|
||||
"""))
|
||||
tmp.ensure("__init__.py")
|
||||
col = py.test.collect.Directory(tmp)
|
||||
l = list(col._tryiter())
|
||||
assert len(l) == 4
|
||||
for numi, i in enumerate(l):
|
||||
for numj, j in enumerate(l):
|
||||
if numj != numi:
|
||||
assert hash(i) != hash(j)
|
||||
assert i != j
|
||||
|
||||
|
||||
def test_check_directory_ordered():
|
||||
tmpdir = py.test.ensuretemp("test_check_directory_ordered")
|
||||
fnames = []
|
||||
for i in range(9, -1, -1):
|
||||
x = tmpdir.ensure("xdir%d" %(i, ), dir=1)
|
||||
fnames.append(x.basename)
|
||||
for i in range(9, -1, -1):
|
||||
x = tmpdir.ensure("test_file%d.py" % (i,))
|
||||
fnames.append(x.basename)
|
||||
fnames.sort()
|
||||
tmpdir.ensure('adir', dir=1)
|
||||
fnames.insert(10, 'adir')
|
||||
col = py.test.collect.Directory(tmpdir)
|
||||
names = col.run()
|
||||
assert names == fnames
|
||||
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
|
||||
import py
|
||||
|
||||
class TestCollectonly:
|
||||
def setup_class(cls):
|
||||
tmp = py.test.ensuretemp('itemgentest')
|
||||
tmp.ensure("__init__.py")
|
||||
tmp.ensure("test_one.py").write(py.code.Source("""
|
||||
def test_one():
|
||||
pass
|
||||
|
||||
class TestX:
|
||||
def test_method_one(self):
|
||||
pass
|
||||
|
||||
class TestY(TestX):
|
||||
pass
|
||||
"""))
|
||||
tmp.ensure("test_two.py").write(py.code.Source("""
|
||||
import py
|
||||
py.test.skip('xxx')
|
||||
"""))
|
||||
tmp.ensure("test_three.py").write("xxxdsadsadsadsa")
|
||||
cls.tmp = tmp
|
||||
|
||||
def test_collectonly(self):
|
||||
config = py.test.config._reparse([self.tmp, '--collectonly'])
|
||||
session = config.initsession()
|
||||
# test it all in once
|
||||
cap = py.io.StdCaptureFD()
|
||||
session.main()
|
||||
out, err = cap.reset()
|
||||
# XXX exact output matching
|
||||
lines = """<Directory 'itemgentest'>
|
||||
<Module 'test_one.py'>
|
||||
<Function 'test_one'>
|
||||
<Class 'TestX'>
|
||||
<Instance '()'>
|
||||
<Function 'test_method_one'>
|
||||
<Class 'TestY'>
|
||||
<Instance '()'>
|
||||
<Function 'test_method_one'>
|
||||
<Module 'test_three.py'>
|
||||
- FAILED TO LOAD MODULE -
|
||||
<Module 'test_two.py'>
|
||||
- skipped -
|
||||
"""
|
||||
for line in lines:
|
||||
assert line in out
|
||||
@@ -1,53 +0,0 @@
|
||||
from __future__ import generators
|
||||
import py
|
||||
from py.__.test.compat import TestCase
|
||||
from py.__.test.outcome import Failed
|
||||
|
||||
class TestCompatTestCaseSetupSemantics(TestCase):
|
||||
globlist = []
|
||||
|
||||
def setUp(self):
|
||||
self.__dict__.setdefault('l', []).append(42)
|
||||
self.globlist.append(self)
|
||||
|
||||
def tearDown(self):
|
||||
self.l.pop()
|
||||
|
||||
def test_issetup(self):
|
||||
l = self.l
|
||||
assert len(l) == 1
|
||||
assert l[-1] == 42
|
||||
#self.checkmultipleinstances()
|
||||
|
||||
def test_issetup2(self):
|
||||
l = self.l
|
||||
assert len(l) == 1
|
||||
assert l[-1] == 42
|
||||
#self.checkmultipleinstances()
|
||||
|
||||
#def checkmultipleinstances(self):
|
||||
# for x,y in zip(self.globlist, self.globlist[1:]):
|
||||
# assert x is not y
|
||||
|
||||
class TestCompatAssertions(TestCase):
|
||||
nameparamdef = {
|
||||
'failUnlessEqual,assertEqual,assertEquals': ('1, 1', '1, 0'),
|
||||
'assertNotEquals,failIfEqual': ('0, 1', '0,0'),
|
||||
'failUnless,assert_': ('1', 'None'),
|
||||
'failIf': ('0', '1'),
|
||||
}
|
||||
|
||||
sourcelist = []
|
||||
for names, (paramok, paramfail) in nameparamdef.items():
|
||||
for name in names.split(','):
|
||||
source = """
|
||||
def test_%(name)s(self):
|
||||
self.%(name)s(%(paramok)s)
|
||||
#self.%(name)s(%(paramfail)s)
|
||||
|
||||
def test_%(name)s_failing(self):
|
||||
self.assertRaises(Failed,
|
||||
self.%(name)s, %(paramfail)s)
|
||||
""" % locals()
|
||||
co = py.code.Source(source).compile()
|
||||
exec co
|
||||
@@ -1,416 +0,0 @@
|
||||
from __future__ import generators
|
||||
import py
|
||||
|
||||
from py.__.test.config import gettopdir
|
||||
|
||||
def test_tmpdir():
|
||||
d1 = py.test.ensuretemp('hello')
|
||||
d2 = py.test.ensuretemp('hello')
|
||||
assert d1 == d2
|
||||
assert d1.check(dir=1)
|
||||
|
||||
def test_config_cmdline_options():
|
||||
o = py.test.ensuretemp('configoptions')
|
||||
o.ensure("conftest.py").write(py.code.Source("""
|
||||
import py
|
||||
def _callback(option, opt_str, value, parser, *args, **kwargs):
|
||||
option.tdest = True
|
||||
Option = py.test.config.Option
|
||||
option = py.test.config.addoptions("testing group",
|
||||
Option('-G', '--glong', action="store", default=42,
|
||||
type="int", dest="gdest", help="g value."),
|
||||
# XXX note: special case, option without a destination
|
||||
Option('-T', '--tlong', action="callback", callback=_callback,
|
||||
help='t value'),
|
||||
)
|
||||
"""))
|
||||
old = o.chdir()
|
||||
try:
|
||||
config = py.test.config._reparse(['-G', '17'])
|
||||
finally:
|
||||
old.chdir()
|
||||
assert config.option.gdest == 17
|
||||
|
||||
def test_config_cmdline_options_only_lowercase():
|
||||
o = py.test.ensuretemp('test_config_cmdline_options_only_lowercase')
|
||||
o.ensure("conftest.py").write(py.code.Source("""
|
||||
import py
|
||||
Option = py.test.config.Option
|
||||
options = py.test.config.addoptions("testing group",
|
||||
Option('-g', '--glong', action="store", default=42,
|
||||
type="int", dest="gdest", help="g value."),
|
||||
)
|
||||
"""))
|
||||
old = o.chdir()
|
||||
try:
|
||||
py.test.raises(ValueError, """
|
||||
py.test.config._reparse(['-g', '17'])
|
||||
""")
|
||||
finally:
|
||||
old.chdir()
|
||||
|
||||
def test_parsing_again_fails():
|
||||
dir = py.test.ensuretemp("parsing_again_fails")
|
||||
config = py.test.config._reparse([str(dir)])
|
||||
py.test.raises(AssertionError, "config.parse([])")
|
||||
|
||||
def test_config_getvalue_honours_conftest():
|
||||
o = py.test.ensuretemp('testconfigget')
|
||||
o.ensure("conftest.py").write("x=1")
|
||||
o.ensure("sub", "conftest.py").write("x=2 ; y = 3")
|
||||
config = py.test.config._reparse([str(o)])
|
||||
assert config.getvalue("x") == 1
|
||||
assert config.getvalue("x", o.join('sub')) == 2
|
||||
py.test.raises(KeyError, "config.getvalue('y')")
|
||||
config = py.test.config._reparse([str(o.join('sub'))])
|
||||
assert config.getvalue("x") == 2
|
||||
assert config.getvalue("y") == 3
|
||||
assert config.getvalue("x", o) == 1
|
||||
py.test.raises(KeyError, 'config.getvalue("y", o)')
|
||||
|
||||
|
||||
def test_siblingconftest_fails_maybe():
|
||||
from py.__.test import config
|
||||
cfg = config.Config()
|
||||
o = py.test.ensuretemp('siblingconftest')
|
||||
o.ensure("__init__.py")
|
||||
o.ensure("sister1", "__init__.py")
|
||||
o.ensure("sister1", "conftest.py").write(py.code.Source("""
|
||||
x = 2
|
||||
"""))
|
||||
|
||||
o.ensure("sister2", "__init__.py")
|
||||
o.ensure("sister2", "conftest.py").write(py.code.Source("""
|
||||
raise SyntaxError
|
||||
"""))
|
||||
|
||||
assert cfg.getvalue(path=o.join('sister1'), name='x') == 2
|
||||
old = o.chdir()
|
||||
try:
|
||||
pytestpath = py.magic.autopath().dirpath().dirpath().dirpath().join(
|
||||
'bin/py.test')
|
||||
print py.process.cmdexec('python "%s" sister1' % (pytestpath,))
|
||||
o.join('sister1').chdir()
|
||||
print py.process.cmdexec('python "%s"' % (pytestpath,))
|
||||
finally:
|
||||
old.chdir()
|
||||
|
||||
def test_config_overwrite():
|
||||
o = py.test.ensuretemp('testconfigget')
|
||||
o.ensure("conftest.py").write("x=1")
|
||||
config = py.test.config._reparse([str(o)])
|
||||
assert config.getvalue('x') == 1
|
||||
config.option.x = 2
|
||||
assert config.getvalue('x') == 2
|
||||
config = py.test.config._reparse([str(o)])
|
||||
assert config.getvalue('x') == 1
|
||||
|
||||
def test_gettopdir():
|
||||
tmp = py.test.ensuretemp("topdir")
|
||||
assert gettopdir([tmp]) == tmp
|
||||
topdir =gettopdir([tmp.join("hello"), tmp.join("world")])
|
||||
assert topdir == tmp
|
||||
|
||||
def test_gettopdir_pypkg():
|
||||
tmp = py.test.ensuretemp("topdir2")
|
||||
a = tmp.ensure('a', dir=1)
|
||||
b = tmp.ensure('a', 'b', '__init__.py')
|
||||
c = tmp.ensure('a', 'b', 'c.py')
|
||||
Z = tmp.ensure('Z', dir=1)
|
||||
assert gettopdir([c]) == a
|
||||
assert gettopdir([c, Z]) == tmp
|
||||
|
||||
|
||||
def test_config_init_direct():
|
||||
tmp = py.test.ensuretemp("_initdirect")
|
||||
tmp.ensure("__init__.py")
|
||||
tmp.ensure("conftest.py").write("x=1 ; y=2")
|
||||
hello = tmp.ensure("test_hello.py")
|
||||
config = py.test.config._reparse([hello])
|
||||
repr = config._makerepr(conftestnames=['x', 'y'])
|
||||
config2 = py.test.config._reparse([tmp.dirpath()])
|
||||
config2._initialized = False # we have to do that from tests
|
||||
config2._initdirect(topdir=tmp.dirpath(), repr=repr)
|
||||
for col1, col2 in zip(config.getcolitems(), config2.getcolitems()):
|
||||
assert col1.fspath == col2.fspath
|
||||
py.test.raises(AssertionError, "config2._initdirect(None, None)")
|
||||
from py.__.test.config import Config
|
||||
config3 = Config()
|
||||
config3._initdirect(topdir=tmp.dirpath(), repr=repr,
|
||||
coltrails=[(tmp.basename, (hello.basename,))])
|
||||
assert config3.getvalue('x') == 1
|
||||
assert config3.getvalue('y') == 2
|
||||
cols = config.getcolitems()
|
||||
assert len(cols) == 1
|
||||
col = cols[0]
|
||||
assert col.name == 'test_hello.py'
|
||||
assert col.parent.name == tmp.basename
|
||||
assert col.parent.parent is None
|
||||
|
||||
def test_config_make_and__mergerepr():
|
||||
tmp = py.test.ensuretemp("reprconfig1")
|
||||
tmp.ensure("__init__.py")
|
||||
tmp.ensure("conftest.py").write("x=1")
|
||||
config = py.test.config._reparse([tmp])
|
||||
repr = config._makerepr(conftestnames=['x'])
|
||||
config.option.verbose = 42
|
||||
repr2 = config._makerepr(conftestnames=[], optnames=['verbose'])
|
||||
config = py.test.config._reparse([tmp.dirpath()])
|
||||
py.test.raises(KeyError, "config.getvalue('x')")
|
||||
config._mergerepr(repr)
|
||||
assert config.getvalue('x') == 1
|
||||
config._mergerepr(repr2)
|
||||
assert config.option.verbose == 42
|
||||
|
||||
def test_config_marshability():
|
||||
tmp = py.test.ensuretemp("configmarshal")
|
||||
tmp.ensure("__init__.py")
|
||||
tmp.ensure("conftest.py").write("a = object()")
|
||||
config = py.test.config._reparse([tmp])
|
||||
py.test.raises(ValueError, "config._makerepr(conftestnames=['a'])")
|
||||
|
||||
config.option.hello = lambda x: None
|
||||
py.test.raises(ValueError, "config._makerepr(conftestnames=[])")
|
||||
config._makerepr(conftestnames=[], optnames=[])
|
||||
|
||||
def test_config_rconfig():
|
||||
tmp = py.test.ensuretemp("rconfigopt")
|
||||
tmp.ensure("__init__.py")
|
||||
tmp.ensure("conftest.py").write(py.code.Source("""
|
||||
import py
|
||||
Option = py.test.config.Option
|
||||
option = py.test.config.addoptions("testing group",
|
||||
Option('-G', '--glong', action="store", default=42,
|
||||
type="int", dest="gdest", help="g value."))
|
||||
"""))
|
||||
config = py.test.config._reparse([tmp, "-G", "11"])
|
||||
assert config.option.gdest == 11
|
||||
repr = config._makerepr(conftestnames=[])
|
||||
config = py.test.config._reparse([tmp.dirpath()])
|
||||
py.test.raises(AttributeError, "config.option.gdest")
|
||||
config._mergerepr(repr)
|
||||
assert config.option.gdest == 11
|
||||
|
||||
class TestSessionAndOptions:
|
||||
def setup_class(cls):
|
||||
cls.tmproot = py.test.ensuretemp(cls.__name__)
|
||||
|
||||
def setup_method(self, method):
|
||||
self.tmpdir = self.tmproot.ensure(method.__name__, dir=1)
|
||||
|
||||
def test_sessionname_default(self):
|
||||
config = py.test.config._reparse([self.tmpdir])
|
||||
assert config._getsessionname() == 'Session'
|
||||
|
||||
def test_sessionname_dist(self):
|
||||
config = py.test.config._reparse([self.tmpdir, '--dist'])
|
||||
assert config._getsessionname() == 'RSession'
|
||||
|
||||
def test_implied_lsession(self):
|
||||
#optnames = 'startserver runbrowser apigen=x rest boxed'.split()
|
||||
#for x in optnames:
|
||||
# config = py.test.config._reparse([self.tmpdir, '--%s' % x])
|
||||
# assert config._getsessionname() == 'LSession'
|
||||
|
||||
for x in 'startserver runbrowser rest'.split():
|
||||
config = py.test.config._reparse([self.tmpdir, '--dist', '--%s' % x])
|
||||
assert config._getsessionname() == 'RSession'
|
||||
|
||||
def test_implied_different_sessions(self):
|
||||
config = py.test.config._reparse([self.tmpdir, '--looponfailing'])
|
||||
assert config._getsessionname() == 'RemoteTerminalSession'
|
||||
config = py.test.config._reparse([self.tmpdir, '--exec=x'])
|
||||
assert config._getsessionname() == 'RemoteTerminalSession'
|
||||
config = py.test.config._reparse([self.tmpdir, '--dist', '--exec=x'])
|
||||
assert config._getsessionname() == 'RSession'
|
||||
config = py.test.config._reparse([self.tmpdir, '--collectonly'])
|
||||
assert config._getsessionname() == 'CollectSession'
|
||||
|
||||
def test_sessionname_lookup_custom(self):
|
||||
self.tmpdir.join("conftest.py").write(py.code.Source("""
|
||||
from py.__.test.session import Session
|
||||
class MySession(Session):
|
||||
def __init__(self, config, reporter=None):
|
||||
self.config = config
|
||||
"""))
|
||||
config = py.test.config._reparse(["--session=MySession", self.tmpdir])
|
||||
session = config.initsession()
|
||||
assert session.__class__.__name__ == 'MySession'
|
||||
|
||||
def test_initsession(self):
|
||||
config = py.test.config._reparse([self.tmpdir])
|
||||
session = config.initsession()
|
||||
assert session.config is config
|
||||
|
||||
def test_boxed_option_default(self):
|
||||
self.tmpdir.join("conftest.py").write("dist_hosts=[]")
|
||||
tmpdir = self.tmpdir.ensure("subdir", dir=1)
|
||||
config = py.test.config._reparse([tmpdir])
|
||||
config.initsession()
|
||||
assert not config.option.boxed
|
||||
config = py.test.config._reparse(['--dist', tmpdir])
|
||||
config.initsession()
|
||||
assert not config.option.boxed
|
||||
|
||||
def test_boxed_option_from_conftest(self):
|
||||
self.tmpdir.join("conftest.py").write("dist_hosts=[]")
|
||||
tmpdir = self.tmpdir.ensure("subdir", dir=1)
|
||||
tmpdir.join("conftest.py").write(py.code.Source("""
|
||||
dist_hosts = []
|
||||
dist_boxed = True
|
||||
"""))
|
||||
config = py.test.config._reparse(['--dist', tmpdir])
|
||||
config.initsession()
|
||||
assert config.option.boxed
|
||||
|
||||
def test_boxed_option_from_conftest2(self):
|
||||
tmpdir = self.tmpdir
|
||||
tmpdir.join("conftest.py").write(py.code.Source("""
|
||||
dist_boxed = False
|
||||
"""))
|
||||
config = py.test.config._reparse([tmpdir, '--box'])
|
||||
assert config.option.boxed
|
||||
config.initsession()
|
||||
assert config.option.boxed
|
||||
|
||||
def test_dist_session_no_capturedisable(self):
|
||||
config = py.test.config._reparse([self.tmpdir, '-d', '-s'])
|
||||
py.test.raises(SystemExit, "config.initsession()")
|
||||
|
||||
def test_getvalue_pathlist(self):
|
||||
tmpdir = self.tmpdir
|
||||
somepath = tmpdir.join("x", "y", "z")
|
||||
p = tmpdir.join("conftest.py")
|
||||
p.write("pathlist = ['.', %r]" % str(somepath))
|
||||
config = py.test.config._reparse([p])
|
||||
assert config.getvalue_pathlist('notexist') is None
|
||||
pl = config.getvalue_pathlist('pathlist')
|
||||
print pl
|
||||
assert len(pl) == 2
|
||||
assert pl[0] == tmpdir
|
||||
assert pl[1] == somepath
|
||||
|
||||
config.option.mypathlist = [py.path.local()]
|
||||
pl = config.getvalue_pathlist('mypathlist')
|
||||
assert pl == [py.path.local()]
|
||||
|
||||
def test_config_iocapturing(self):
|
||||
self.tmpdir
|
||||
config = py.test.config._reparse([self.tmpdir])
|
||||
assert config.getvalue("conf_iocapture")
|
||||
tmpdir = self.tmpdir.ensure("sub-with-conftest", dir=1)
|
||||
tmpdir.join("conftest.py").write(py.code.Source("""
|
||||
conf_iocapture = "sys"
|
||||
"""))
|
||||
config = py.test.config._reparse([tmpdir])
|
||||
assert config.getvalue("conf_iocapture") == "sys"
|
||||
class dummy: pass
|
||||
config._startcapture(dummy)
|
||||
print 42
|
||||
py.std.os.write(1, "23")
|
||||
config._finishcapture(dummy)
|
||||
assert dummy._captured_out.strip() == "42"
|
||||
|
||||
config = py.test.config._reparse([tmpdir.dirpath()])
|
||||
config._startcapture(dummy, path=tmpdir)
|
||||
print 42
|
||||
py.std.os.write(1, "23")
|
||||
config._finishcapture(dummy)
|
||||
assert dummy._captured_out.strip() == "42"
|
||||
|
||||
class TestConfigColitems:
|
||||
def setup_class(cls):
|
||||
cls.tmproot = py.test.ensuretemp(cls.__name__)
|
||||
|
||||
def setup_method(self, method):
|
||||
self.tmpdir = self.tmproot.mkdir(method.__name__)
|
||||
|
||||
def test_getcolitems_onedir(self):
|
||||
config = py.test.config._reparse([self.tmpdir])
|
||||
colitems = config.getcolitems()
|
||||
assert len(colitems) == 1
|
||||
col = colitems[0]
|
||||
assert isinstance(col, py.test.collect.Directory)
|
||||
for col in col.listchain():
|
||||
assert col._config is config
|
||||
|
||||
def test_getcolitems_twodirs(self):
|
||||
config = py.test.config._reparse([self.tmpdir, self.tmpdir])
|
||||
colitems = config.getcolitems()
|
||||
assert len(colitems) == 2
|
||||
col1, col2 = colitems
|
||||
assert col1.name == col2.name
|
||||
assert col1.parent == col2.parent
|
||||
|
||||
def test_getcolitems_curdir_and_subdir(self):
|
||||
a = self.tmpdir.ensure("a", dir=1)
|
||||
config = py.test.config._reparse([self.tmpdir, a])
|
||||
colitems = config.getcolitems()
|
||||
assert len(colitems) == 2
|
||||
col1, col2 = colitems
|
||||
assert col1.name == self.tmpdir.basename
|
||||
assert col2.name == 'a'
|
||||
for col in colitems:
|
||||
for subcol in col.listchain():
|
||||
assert col._config is config
|
||||
|
||||
def test__getcol_global_file(self):
|
||||
x = self.tmpdir.ensure("x.py")
|
||||
config = py.test.config._reparse([x])
|
||||
col = config._getcollector(x)
|
||||
assert isinstance(col, py.test.collect.Module)
|
||||
assert col.name == 'x.py'
|
||||
assert col.parent.name == self.tmpdir.basename
|
||||
assert col.parent.parent is None
|
||||
for col in col.listchain():
|
||||
assert col._config is config
|
||||
|
||||
def test__getcol_global_dir(self):
|
||||
x = self.tmpdir.ensure("a", dir=1)
|
||||
config = py.test.config._reparse([x])
|
||||
col = config._getcollector(x)
|
||||
assert isinstance(col, py.test.collect.Directory)
|
||||
print col.listchain()
|
||||
assert col.name == 'a'
|
||||
assert col.parent is None
|
||||
assert col._config is config
|
||||
|
||||
def test__getcol_pkgfile(self):
|
||||
x = self.tmpdir.ensure("x.py")
|
||||
self.tmpdir.ensure("__init__.py")
|
||||
config = py.test.config._reparse([x])
|
||||
col = config._getcollector(x)
|
||||
assert isinstance(col, py.test.collect.Module)
|
||||
assert col.name == 'x.py'
|
||||
assert col.parent.name == x.dirpath().basename
|
||||
assert col.parent.parent is None
|
||||
for col in col.listchain():
|
||||
assert col._config is config
|
||||
|
||||
def test_get_collector_trail_and_back(self):
|
||||
a = self.tmpdir.ensure("a", dir=1)
|
||||
self.tmpdir.ensure("a", "__init__.py")
|
||||
x = self.tmpdir.ensure("a", "trail.py")
|
||||
config = py.test.config._reparse([x])
|
||||
col = config._getcollector(x)
|
||||
trail = config.get_collector_trail(col)
|
||||
assert len(trail) == 2
|
||||
assert trail[0] == a.relto(config.topdir)
|
||||
assert trail[1] == ('trail.py',)
|
||||
col2 = config._getcollector(trail)
|
||||
assert col2.listnames() == col.listnames()
|
||||
|
||||
def test_get_collector_trail_topdir_and_beyond(self):
|
||||
config = py.test.config._reparse([self.tmpdir])
|
||||
col = config._getcollector(config.topdir)
|
||||
trail = config.get_collector_trail(col)
|
||||
assert len(trail) == 2
|
||||
assert trail[0] == '.'
|
||||
assert trail[1] == ()
|
||||
col2 = config._getcollector(trail)
|
||||
assert col2.fspath == config.topdir
|
||||
assert len(col2.listchain()) == 1
|
||||
col3 = config._getcollector(config.topdir.dirpath())
|
||||
py.test.raises(ValueError,
|
||||
"config.get_collector_trail(col3)")
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import py
|
||||
from py.__.test.conftesthandle import Conftest
|
||||
|
||||
class TestConftestValueAccessGlobal:
|
||||
def setup_class(cls):
|
||||
# if we have "global" conftests (i.e. no __init__.py
|
||||
# and thus no further import scope) it should still all work
|
||||
# because "global" conftests are imported with a
|
||||
# mangled module name (related to their actual path)
|
||||
cls.basedir = d = py.test.ensuretemp(cls.__name__)
|
||||
d.ensure("adir/conftest.py").write("a=1 ; Directory = 3")
|
||||
d.ensure("adir/b/conftest.py").write("b=2 ; a = 1.5")
|
||||
|
||||
def test_basic_init(self):
|
||||
conftest = Conftest()
|
||||
conftest.setinitial([self.basedir.join("adir")])
|
||||
assert conftest.rget("a") == 1
|
||||
|
||||
def test_immediate_initialiation_and_incremental_are_the_same(self):
|
||||
conftest = Conftest()
|
||||
snap0 = len(conftest._path2confmods)
|
||||
conftest.getconftestmodules(self.basedir)
|
||||
snap1 = len(conftest._path2confmods)
|
||||
#assert len(conftest._path2confmods) == snap1 + 1
|
||||
conftest.getconftestmodules(self.basedir.join('adir'))
|
||||
assert len(conftest._path2confmods) == snap1 + 1
|
||||
conftest.getconftestmodules(self.basedir.join('b'))
|
||||
assert len(conftest._path2confmods) == snap1 + 2
|
||||
|
||||
def test_default_Module_setting_is_visible_always(self):
|
||||
for path in self.basedir.parts():
|
||||
conftest = Conftest(path)
|
||||
#assert conftest.lget("Module") == py.test.collect.Module
|
||||
assert conftest.rget("Module") == py.test.collect.Module
|
||||
|
||||
def test_default_has_lower_prio(self):
|
||||
conftest = Conftest(self.basedir.join("adir"))
|
||||
assert conftest.rget('Directory') == 3
|
||||
#assert conftest.lget('Directory') == py.test.collect.Directory
|
||||
|
||||
def test_value_access_not_existing(self):
|
||||
conftest = Conftest(self.basedir)
|
||||
py.test.raises(KeyError, "conftest.rget('a')")
|
||||
#py.test.raises(KeyError, "conftest.lget('a')")
|
||||
|
||||
def test_value_access_by_path(self):
|
||||
conftest = Conftest(self.basedir)
|
||||
assert conftest.rget("a", self.basedir.join('adir')) == 1
|
||||
#assert conftest.lget("a", self.basedir.join('adir')) == 1
|
||||
assert conftest.rget("a", self.basedir.join('adir', 'b')) == 1.5
|
||||
#assert conftest.lget("a", self.basedir.join('adir', 'b')) == 1
|
||||
#assert conftest.lget("b", self.basedir.join('adir', 'b')) == 2
|
||||
#assert py.test.raises(KeyError,
|
||||
# 'conftest.lget("b", self.basedir.join("a"))'
|
||||
#)
|
||||
|
||||
def test_value_access_with_init_one_conftest(self):
|
||||
conftest = Conftest(self.basedir.join('adir'))
|
||||
assert conftest.rget("a") == 1
|
||||
#assert conftest.lget("a") == 1
|
||||
|
||||
def test_value_access_with_init_two_conftests(self):
|
||||
conftest = Conftest(self.basedir.join("adir", "b"))
|
||||
conftest.rget("a") == 1.5
|
||||
#conftest.lget("a") == 1
|
||||
#conftest.lget("b") == 1
|
||||
|
||||
def test_value_access_with_confmod(self):
|
||||
topdir = self.basedir.join("adir", "b")
|
||||
topdir.ensure("xx", dir=True)
|
||||
conftest = Conftest(topdir)
|
||||
mod, value = conftest.rget_with_confmod("a", topdir)
|
||||
assert value == 1.5
|
||||
path = py.path.local(mod.__file__)
|
||||
assert path.dirpath() == self.basedir.join("adir", "b")
|
||||
assert path.purebasename == "conftest"
|
||||
|
||||
class TestConftestValueAccessInPackage(TestConftestValueAccessGlobal):
|
||||
def setup_class(cls):
|
||||
TestConftestValueAccessGlobal.__dict__['setup_class'](cls)
|
||||
d = cls.basedir
|
||||
d.ensure("adir/__init__.py")
|
||||
d.ensure("adir/b/__init__.py")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import py
|
||||
|
||||
def dep(i):
|
||||
if i == 0:
|
||||
py.std.warnings.warn("is deprecated", DeprecationWarning)
|
||||
|
||||
reg = {}
|
||||
def dep_explicit(i):
|
||||
if i == 0:
|
||||
py.std.warnings.warn_explicit("dep_explicit", category=DeprecationWarning,
|
||||
filename="hello", lineno=3)
|
||||
|
||||
def test_deprecated_call_raises():
|
||||
py.test.raises(AssertionError,
|
||||
"py.test.deprecated_call(dep, 3)")
|
||||
|
||||
def test_deprecated_call():
|
||||
py.test.deprecated_call(dep, 0)
|
||||
|
||||
def test_deprecated_call_preserves():
|
||||
r = py.std.warnings.onceregistry.copy()
|
||||
f = py.std.warnings.filters[:]
|
||||
test_deprecated_call_raises()
|
||||
test_deprecated_call()
|
||||
assert r == py.std.warnings.onceregistry
|
||||
assert f == py.std.warnings.filters
|
||||
|
||||
def test_deprecated_explicit_call_raises():
|
||||
py.test.raises(AssertionError,
|
||||
"py.test.deprecated_call(dep_explicit, 3)")
|
||||
|
||||
def test_deprecated_explicit_call():
|
||||
py.test.deprecated_call(dep_explicit, 0)
|
||||
py.test.deprecated_call(dep_explicit, 0)
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
|
||||
import py
|
||||
from py.__.test.outcome import Skipped, Failed, Passed, Outcome
|
||||
|
||||
|
||||
def setup_module(mod):
|
||||
mod.tmp = py.test.ensuretemp(__name__)
|
||||
|
||||
def test_simple_docteststring():
|
||||
p = tmp.join("test_simple_docteststring")
|
||||
p.write(py.code.Source("""
|
||||
>>> i = 0
|
||||
>>> i + 1
|
||||
1
|
||||
"""))
|
||||
testitem = py.test.collect.DoctestFile(p).join(p.basename)
|
||||
res = testitem.run()
|
||||
assert res is None
|
||||
|
||||
def test_simple_docteststring_failing():
|
||||
p = tmp.join("test_simple_docteststring_failing")
|
||||
p.write(py.code.Source("""
|
||||
>>> i = 0
|
||||
>>> i + 1
|
||||
2
|
||||
"""))
|
||||
testitem = py.test.collect.DoctestFile(p).join(p.basename)
|
||||
py.test.raises(Failed, "testitem.run()")
|
||||
|
||||
|
||||
def test_collect_doctest_files_with_test_prefix():
|
||||
o = py.test.ensuretemp("testdoctest")
|
||||
checkfile = o.ensure("test_something.txt")
|
||||
o.ensure("whatever.txt")
|
||||
checkfile.write(py.code.Source("""
|
||||
alskdjalsdk
|
||||
>>> i = 5
|
||||
>>> i-1
|
||||
4
|
||||
"""))
|
||||
for x in (o, checkfile):
|
||||
#print "checking that %s returns custom items" % (x,)
|
||||
config = py.test.config._reparse([x])
|
||||
col = config._getcollector(x)
|
||||
items = list(col._tryiter(py.test.collect.Item))
|
||||
assert len(items) == 1
|
||||
assert isinstance(items[0].parent, py.test.collect.DoctestFile)
|
||||
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
|
||||
import py
|
||||
import example1
|
||||
|
||||
from py.__.test.executor import RunExecutor, BoxExecutor,\
|
||||
AsyncExecutor, ApigenExecutor
|
||||
from py.__.test.outcome import ReprOutcome
|
||||
from py.__.test.rsession.testing.basetest import BasicRsessionTest
|
||||
from py.__.test.outcome import Failed
|
||||
|
||||
def setup_module(mod):
|
||||
if py.std.sys.platform == "win32":
|
||||
py.test.skip("skipping executor tests (some require os.fork)")
|
||||
|
||||
class Item(py.test.collect.Item):
|
||||
def __init__(self, name, config):
|
||||
super(Item, self).__init__(name)
|
||||
self._config = config
|
||||
|
||||
class ItemTestPassing(Item):
|
||||
def run(self):
|
||||
return None
|
||||
|
||||
class ItemTestFailing(Item):
|
||||
def run(self):
|
||||
assert 0 == 1
|
||||
|
||||
class ItemTestSkipping(Item):
|
||||
def run(self):
|
||||
py.test.skip("hello")
|
||||
|
||||
class ItemTestPrinting(Item):
|
||||
def run(self):
|
||||
print "hello"
|
||||
|
||||
class ItemTestFailingExplicit(Item):
|
||||
def run(self):
|
||||
raise Failed(excinfo="3")
|
||||
|
||||
class ItemTestFailingExplicitEmpty(Item):
|
||||
def run(self):
|
||||
py.test.raises(ValueError, lambda : 123)
|
||||
|
||||
class TestExecutor(BasicRsessionTest):
|
||||
def test_run_executor(self):
|
||||
ex = RunExecutor(ItemTestPassing("pass", self.config), config=self.config)
|
||||
outcome = ex.execute()
|
||||
assert outcome.passed
|
||||
|
||||
ex = RunExecutor(ItemTestFailing("fail", self.config), config=self.config)
|
||||
outcome = ex.execute()
|
||||
assert not outcome.passed
|
||||
|
||||
ex = RunExecutor(ItemTestSkipping("skip", self.config), config=self.config)
|
||||
outcome = ex.execute()
|
||||
assert outcome.skipped
|
||||
assert not outcome.passed
|
||||
assert not outcome.excinfo
|
||||
|
||||
def test_run_executor_capture(self):
|
||||
ex = RunExecutor(ItemTestPrinting("print", self.config), config=self.config)
|
||||
outcome = ex.execute()
|
||||
assert outcome.stdout == "hello\n"
|
||||
|
||||
def test_box_executor(self):
|
||||
ex = BoxExecutor(ItemTestPassing("pass", self.config), config=self.config)
|
||||
outcome_repr = ex.execute()
|
||||
outcome = ReprOutcome(outcome_repr)
|
||||
assert outcome.passed
|
||||
|
||||
ex = BoxExecutor(ItemTestFailing("fail", self.config), config=self.config)
|
||||
outcome_repr = ex.execute()
|
||||
outcome = ReprOutcome(outcome_repr)
|
||||
assert not outcome.passed
|
||||
|
||||
ex = BoxExecutor(ItemTestSkipping("skip", self.config), config=self.config)
|
||||
outcome_repr = ex.execute()
|
||||
outcome = ReprOutcome(outcome_repr)
|
||||
assert outcome.skipped
|
||||
assert not outcome.passed
|
||||
assert not outcome.excinfo
|
||||
|
||||
def test_box_executor_stdout(self):
|
||||
item = self.getexample("print")
|
||||
ex = BoxExecutor(item, config=self.config)
|
||||
outcome_repr = ex.execute()
|
||||
outcome = ReprOutcome(outcome_repr)
|
||||
assert outcome.passed
|
||||
assert outcome.stdout.find("samfing") != -1
|
||||
|
||||
def test_box_executor_stdout_error(self):
|
||||
item = self.getexample("printfail")
|
||||
ex = BoxExecutor(item, config=self.config)
|
||||
outcome_repr = ex.execute()
|
||||
outcome = ReprOutcome(outcome_repr)
|
||||
assert not outcome.passed
|
||||
assert outcome.stdout.find("samfing elz") != -1
|
||||
|
||||
def test_cont_executor(self):
|
||||
item = self.getexample("printfail")
|
||||
ex = AsyncExecutor(item, config=self.config)
|
||||
cont, pid = ex.execute()
|
||||
assert pid
|
||||
outcome_repr = cont()
|
||||
outcome = ReprOutcome(outcome_repr)
|
||||
assert not outcome.passed
|
||||
assert outcome.stdout.find("samfing elz") != -1
|
||||
|
||||
def test_apigen_executor(self):
|
||||
class Tracer(object):
|
||||
def __init__(self):
|
||||
self.starts = 0
|
||||
self.ends = 0
|
||||
|
||||
def start_tracing(self):
|
||||
self.starts += 1
|
||||
|
||||
def end_tracing(self):
|
||||
self.ends += 1
|
||||
|
||||
tmpdir = py.test.ensuretemp("apigen_executor")
|
||||
tmpdir.ensure("__init__.py")
|
||||
tmpdir.ensure("test_one.py").write(py.code.Source("""
|
||||
def g():
|
||||
pass
|
||||
|
||||
def test_1():
|
||||
g()
|
||||
|
||||
class TestX(object):
|
||||
def setup_method(self, m):
|
||||
self.ttt = 1
|
||||
|
||||
def test_one(self):
|
||||
self.ttt += 1
|
||||
|
||||
def test_raise(self):
|
||||
1/0
|
||||
"""))
|
||||
config = py.test.config._reparse([tmpdir])
|
||||
rootcol = config._getcollector(tmpdir)
|
||||
tracer = Tracer()
|
||||
item = rootcol._getitembynames("test_one.py/test_1")
|
||||
ex = ApigenExecutor(item, config=config)
|
||||
out1 = ex.execute(tracer)
|
||||
item = rootcol._getitembynames("test_one.py/TestX/()/test_one")
|
||||
ex = ApigenExecutor(item, config=config)
|
||||
out2 = ex.execute(tracer)
|
||||
item = rootcol._getitembynames("test_one.py/TestX/()/test_raise")
|
||||
ex = ApigenExecutor(item, config=config)
|
||||
out3 = ex.execute(tracer)
|
||||
assert tracer.starts == 3
|
||||
assert tracer.ends == 3
|
||||
assert out1.passed
|
||||
assert out2.passed
|
||||
assert not out3.passed
|
||||
|
||||
def test_executor_explicit_Failed(self):
|
||||
ex = RunExecutor(ItemTestFailingExplicit("failex", self.config),
|
||||
config=self.config)
|
||||
|
||||
outcome = ex.execute()
|
||||
assert not outcome.passed
|
||||
assert outcome.excinfo == "3"
|
||||
|
||||
def test_executor_explicit_Faile_no_excinfo(self):
|
||||
ex = RunExecutor(ItemTestFailingExplicitEmpty("failexx", self.config),
|
||||
config=self.config)
|
||||
outcome = ex.execute()
|
||||
assert not outcome.passed
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
|
||||
import py
|
||||
from py.__.test.session import itemgen
|
||||
from py.__.test import repevent
|
||||
|
||||
class TestItemgen:
|
||||
def setup_class(cls):
|
||||
tmp = py.test.ensuretemp('itemgentest')
|
||||
tmp.ensure("__init__.py")
|
||||
tmp.ensure("test_one.py").write(py.code.Source("""
|
||||
def test_one():
|
||||
pass
|
||||
|
||||
class TestX:
|
||||
def test_method_one(self):
|
||||
pass
|
||||
|
||||
class TestY(TestX):
|
||||
pass
|
||||
"""))
|
||||
tmp.ensure("test_two.py").write(py.code.Source("""
|
||||
import py
|
||||
py.test.skip('xxx')
|
||||
"""))
|
||||
tmp.ensure("test_three.py").write("xxxdsadsadsadsa")
|
||||
cls.tmp = tmp
|
||||
|
||||
def test_itemgen(self):
|
||||
l = []
|
||||
colitems = [py.test.collect.Directory(self.tmp)]
|
||||
gen = itemgen(None, colitems, l.append)
|
||||
items = [i for i in gen]
|
||||
assert len([i for i in l if isinstance(i, repevent.SkippedTryiter)]) == 1
|
||||
assert len([i for i in l if isinstance(i, repevent.FailedTryiter)]) == 1
|
||||
assert len(items) == 3
|
||||
assert items[0].name == 'test_one'
|
||||
assert items[1].name == 'test_method_one'
|
||||
assert items[2].name == 'test_method_one'
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
|
||||
import py
|
||||
from py.__.test.outcome import SerializableOutcome, ReprOutcome, ExcInfoRepr
|
||||
|
||||
import marshal
|
||||
import py
|
||||
|
||||
def test_critical_debugging_flag():
|
||||
outcome = SerializableOutcome(is_critical=True)
|
||||
r = ReprOutcome(outcome.make_repr())
|
||||
assert r.is_critical
|
||||
|
||||
def f1():
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
raise ValueError(42)
|
||||
|
||||
def f2():
|
||||
f1()
|
||||
|
||||
def f3():
|
||||
f2()
|
||||
|
||||
def f4():
|
||||
py.test.skip("argh!")
|
||||
|
||||
def test_exception_info_repr():
|
||||
try:
|
||||
f3()
|
||||
except:
|
||||
outcome = SerializableOutcome(excinfo=py.code.ExceptionInfo())
|
||||
|
||||
repr = outcome.make_excinfo_repr(outcome.excinfo, "long")
|
||||
assert marshal.dumps(repr)
|
||||
excinfo = ExcInfoRepr(repr)
|
||||
|
||||
assert str(excinfo.typename) == "ValueError"
|
||||
assert str(excinfo.value) == "42"
|
||||
assert len(excinfo.traceback) == 4
|
||||
myfile = py.magic.autopath()
|
||||
assert excinfo.traceback[3].path == myfile
|
||||
assert excinfo.traceback[3].lineno == f1.func_code.co_firstlineno + 4
|
||||
assert excinfo.traceback[3].relline == 5
|
||||
assert excinfo.traceback[2].path == myfile
|
||||
assert excinfo.traceback[2].lineno == f2.func_code.co_firstlineno
|
||||
assert excinfo.traceback[2].relline == 1
|
||||
assert excinfo.traceback[1].path == myfile
|
||||
assert excinfo.traceback[1].lineno == f3.func_code.co_firstlineno
|
||||
assert excinfo.traceback[1].relline == 1
|
||||
|
||||
def test_packed_skipped():
|
||||
try:
|
||||
f4()
|
||||
except:
|
||||
outcome = SerializableOutcome(skipped=py.code.ExceptionInfo())
|
||||
repr = outcome.make_excinfo_repr(outcome.skipped, "long")
|
||||
assert marshal.dumps(repr)
|
||||
skipped = ExcInfoRepr(repr)
|
||||
assert skipped.value == "'argh!'"
|
||||
|
||||
#def test_f3():
|
||||
# f3()
|
||||
@@ -1,18 +0,0 @@
|
||||
from py import test
|
||||
|
||||
def somefunc(x, y):
|
||||
assert x == y
|
||||
|
||||
class TestClass:
|
||||
def test_raises(self):
|
||||
test.raises(ValueError, "int('qwe')")
|
||||
|
||||
def test_raises_exec(self):
|
||||
test.raises(ValueError, "a,x = []")
|
||||
|
||||
def test_raises_syntax_error(self):
|
||||
test.raises(SyntaxError, "qwe qwe qwe")
|
||||
|
||||
def test_raises_function(self):
|
||||
test.raises(ValueError, int, 'hello')
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import py
|
||||
from py.__.test.testing.setupdata import setup_module
|
||||
|
||||
class TestRemote:
|
||||
def test_exec(self):
|
||||
o = tmpdir.ensure('remote', dir=1)
|
||||
tfile = o.join('test_exec.py')
|
||||
tfile.write(py.code.Source("""
|
||||
def test_1():
|
||||
assert 1 == 0
|
||||
"""))
|
||||
print py.std.sys.executable
|
||||
config = py.test.config._reparse(
|
||||
['--exec=' + py.std.sys.executable,
|
||||
o])
|
||||
cls = config._getsessionclass()
|
||||
out = [] # out = py.std.Queue.Queue()
|
||||
session = cls(config, out.append)
|
||||
failures = session.main()
|
||||
for s in out:
|
||||
if s.find('1 failed') != -1:
|
||||
break
|
||||
else:
|
||||
py.test.fail("did not see test_1 failure in output")
|
||||
assert failures
|
||||
|
||||
def test_looponfailing(self):
|
||||
o = tmpdir.ensure('looponfailing', dir=1)
|
||||
tfile = o.join('test_looponfailing.py')
|
||||
tfile.write(py.code.Source("""
|
||||
def test_1():
|
||||
assert 1 == 0
|
||||
"""))
|
||||
print py.std.sys.executable
|
||||
config = py.test.config._reparse(['--looponfailing', str(o)])
|
||||
cls = config._getsessionclass()
|
||||
out = py.std.Queue.Queue()
|
||||
session = cls(config, out.put)
|
||||
pool = py._thread.WorkerPool()
|
||||
reply = pool.dispatch(session.main)
|
||||
while 1:
|
||||
s = out.get(timeout=5.0)
|
||||
if s.find('1 failed') != -1:
|
||||
break
|
||||
print s
|
||||
else:
|
||||
py.test.fail("did not see test_1 failure")
|
||||
# XXX we would like to have a cleaner way to finish
|
||||
try:
|
||||
reply.get(timeout=5.0)
|
||||
except IOError, e:
|
||||
assert str(e).lower().find('timeout') != -1
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
""" test reporting functionality. """
|
||||
|
||||
import py
|
||||
from py.__.test import repevent
|
||||
|
||||
def test_wrapcall_ok():
|
||||
l = []
|
||||
def ok(x):
|
||||
return x+1
|
||||
i = repevent.wrapcall(l.append, ok, 1)
|
||||
assert i == 2
|
||||
assert len(l) == 2
|
||||
assert isinstance(l[0], repevent.CallStart)
|
||||
assert isinstance(l[1], repevent.CallFinish)
|
||||
assert repr(l[0])
|
||||
assert repr(l[1])
|
||||
|
||||
def test_wrapcall_exception():
|
||||
l = []
|
||||
def fail(x):
|
||||
raise ValueError
|
||||
py.test.raises(ValueError, "repevent.wrapcall(l.append, fail, 1)")
|
||||
assert len(l) == 2
|
||||
assert isinstance(l[0], repevent.CallStart)
|
||||
assert isinstance(l[1], repevent.CallException)
|
||||
|
||||
def test_reporter_methods_sanity():
|
||||
""" Checks if all the methods of reporter are sane
|
||||
"""
|
||||
from py.__.test.reporter import RemoteReporter
|
||||
|
||||
for method in dir(RemoteReporter):
|
||||
|
||||
if method.startswith("report_") and method != "report_unknown":
|
||||
assert method[len('report_'):] in repevent.__dict__
|
||||
|
||||
def test_repevent_failures():
|
||||
from py.__.test.outcome import SerializableOutcome, ReprOutcome
|
||||
|
||||
assert not repevent.ReportEvent().is_failure()
|
||||
assert not repevent.CallEvent(None, None, None).is_failure()
|
||||
assert repevent.FailedTryiter(None, None).is_failure()
|
||||
out = ReprOutcome(SerializableOutcome().make_repr())
|
||||
assert not repevent.ReceivedItemOutcome(None, None, out).is_failure()
|
||||
out = ReprOutcome(SerializableOutcome(skipped="xxx").make_repr())
|
||||
assert not repevent.ReceivedItemOutcome(None, None, out).is_failure()
|
||||
try:
|
||||
1/0
|
||||
except:
|
||||
exc = py.code.ExceptionInfo()
|
||||
out = ReprOutcome(SerializableOutcome(excinfo=exc).make_repr())
|
||||
assert repevent.ReceivedItemOutcome(None, None, out).is_failure()
|
||||
|
||||
@@ -1,278 +0,0 @@
|
||||
|
||||
""" reporter tests.
|
||||
|
||||
XXX there are a few disabled reporting tests because
|
||||
they test for exact formatting as far as i can see.
|
||||
I think it's rather better to directly invoke a
|
||||
reporter and pass it some hand-prepared events to see
|
||||
that running the reporter doesn't break shallowly.
|
||||
|
||||
Otherwise, i suppose that some "visual" testing can usually be driven
|
||||
manually by user-input. And when passing particular events
|
||||
to a reporter it's also easier to check for one line
|
||||
instead of having to know the order in which things are printed
|
||||
etc.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
||||
import py, os
|
||||
from py.__.test.session import AbstractSession, itemgen
|
||||
from py.__.test.reporter import RemoteReporter, LocalReporter, choose_reporter
|
||||
from py.__.test import repevent
|
||||
from py.__.test.outcome import ReprOutcome, SerializableOutcome
|
||||
from py.__.test.rsession.hostmanage import HostInfo
|
||||
from py.__.test.box import Box
|
||||
from py.__.test.rsession.testing.basetest import BasicRsessionTest
|
||||
import sys
|
||||
from StringIO import StringIO
|
||||
|
||||
class MockSession(object):
|
||||
def __init__(self, reporter):
|
||||
self.reporter = reporter
|
||||
|
||||
def start(self, item):
|
||||
self.reporter(repevent.ItemStart(item))
|
||||
|
||||
def finish(self, item):
|
||||
pass
|
||||
|
||||
class DummyGateway(object):
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
|
||||
class DummyChannel(object):
|
||||
def __init__(self, host):
|
||||
self.gateway = DummyGateway(host)
|
||||
|
||||
class AbstractTestReporter(BasicRsessionTest):
|
||||
def prepare_outcomes(self):
|
||||
# possible outcomes
|
||||
try:
|
||||
1/0
|
||||
except:
|
||||
exc = py.code.ExceptionInfo()
|
||||
|
||||
try:
|
||||
py.test.skip("xxx")
|
||||
except:
|
||||
skipexc = py.code.ExceptionInfo()
|
||||
|
||||
outcomes = [SerializableOutcome(()),
|
||||
SerializableOutcome(skipped=skipexc),
|
||||
SerializableOutcome(excinfo=exc),
|
||||
SerializableOutcome()]
|
||||
|
||||
outcomes = [ReprOutcome(outcome.make_repr()) for outcome in outcomes]
|
||||
outcomes[3].signal = 11
|
||||
outcomes[0].passed = False
|
||||
|
||||
return outcomes
|
||||
|
||||
def report_received_item_outcome(self):
|
||||
item = self.getexample("pass")
|
||||
outcomes = self.prepare_outcomes()
|
||||
|
||||
def boxfun(config, item, outcomes):
|
||||
hosts = self.get_hosts()
|
||||
r = self.reporter(config, hosts)
|
||||
if hosts:
|
||||
ch = DummyChannel(hosts[0])
|
||||
else:
|
||||
ch = None
|
||||
for outcome in outcomes:
|
||||
r.report(repevent.ReceivedItemOutcome(ch, item, outcome))
|
||||
|
||||
cap = py.io.StdCaptureFD()
|
||||
boxfun(self.config, item, outcomes)
|
||||
out, err = cap.reset()
|
||||
assert not err
|
||||
return out
|
||||
|
||||
def _test_module(self):
|
||||
funcitem = self.getexample("pass")
|
||||
moditem = self.getmod()
|
||||
outcomes = self.prepare_outcomes()
|
||||
|
||||
def boxfun(config, item, funcitem, outcomes):
|
||||
hosts = self.get_hosts()
|
||||
r = self.reporter(config, hosts)
|
||||
r.report(repevent.ItemStart(item))
|
||||
if hosts:
|
||||
ch = DummyChannel(hosts[0])
|
||||
else:
|
||||
ch = None
|
||||
for outcome in outcomes:
|
||||
r.report(repevent.ReceivedItemOutcome(ch, funcitem, outcome))
|
||||
|
||||
cap = py.io.StdCaptureFD()
|
||||
boxfun(self.config, moditem, funcitem, outcomes)
|
||||
out, err = cap.reset()
|
||||
assert not err
|
||||
return out
|
||||
|
||||
def _test_full_module(self):
|
||||
tmpdir = py.test.ensuretemp("repmod")
|
||||
tmpdir.ensure("__init__.py")
|
||||
tmpdir.ensure("test_one.py").write(py.code.Source("""
|
||||
def test_x():
|
||||
pass
|
||||
"""))
|
||||
tmpdir.ensure("test_two.py").write(py.code.Source("""
|
||||
import py
|
||||
py.test.skip("reason")
|
||||
"""))
|
||||
tmpdir.ensure("test_three.py").write(py.code.Source("""
|
||||
sadsadsa
|
||||
"""))
|
||||
|
||||
def boxfun():
|
||||
config = py.test.config._reparse([str(tmpdir)])
|
||||
rootcol = py.test.collect.Directory(tmpdir)
|
||||
hosts = self.get_hosts()
|
||||
r = self.reporter(config, hosts)
|
||||
list(itemgen(MockSession(r), [rootcol], r.report))
|
||||
|
||||
cap = py.io.StdCaptureFD()
|
||||
boxfun()
|
||||
out, err = cap.reset()
|
||||
assert not err
|
||||
return out
|
||||
|
||||
def test_failed_to_load(self):
|
||||
tmpdir = py.test.ensuretemp("failedtoload")
|
||||
tmpdir.ensure("__init__.py")
|
||||
tmpdir.ensure("test_three.py").write(py.code.Source("""
|
||||
sadsadsa
|
||||
"""))
|
||||
def boxfun():
|
||||
config = py.test.config._reparse([str(tmpdir)])
|
||||
rootcol = py.test.collect.Directory(tmpdir)
|
||||
hosts = self.get_hosts()
|
||||
r = self.reporter(config, hosts)
|
||||
r.report(repevent.TestStarted(hosts, config, ["a"]))
|
||||
r.report(repevent.RsyncFinished())
|
||||
list(itemgen(MockSession(r), [rootcol], r.report))
|
||||
r.report(repevent.TestFinished())
|
||||
return r
|
||||
|
||||
cap = py.io.StdCaptureFD()
|
||||
r = boxfun()
|
||||
out, err = cap.reset()
|
||||
assert not err
|
||||
assert out.find("1 failed in") != -1
|
||||
assert out.find("NameError: name 'sadsadsa' is not defined") != -1
|
||||
|
||||
def _test_verbose(self):
|
||||
tmpdir = py.test.ensuretemp("reporterverbose")
|
||||
tmpdir.ensure("__init__.py")
|
||||
tmpdir.ensure("test_one.py").write("def test_x(): pass")
|
||||
cap = py.io.StdCaptureFD()
|
||||
config = py.test.config._reparse([str(tmpdir), '-v'])
|
||||
hosts = self.get_hosts()
|
||||
r = self.reporter(config, hosts)
|
||||
r.report(repevent.TestStarted(hosts, config, []))
|
||||
r.report(repevent.RsyncFinished())
|
||||
rootcol = py.test.collect.Directory(tmpdir)
|
||||
list(itemgen(MockSession(r), [rootcol], r.report))
|
||||
r.report(repevent.TestFinished())
|
||||
out, err = cap.reset()
|
||||
assert not err
|
||||
for i in ['+ testmodule:', 'test_one.py[1]']: # XXX finish
|
||||
assert i in out
|
||||
|
||||
def _test_still_to_go(self):
|
||||
tmpdir = py.test.ensuretemp("stilltogo")
|
||||
tmpdir.ensure("__init__.py")
|
||||
cap = py.io.StdCaptureFD()
|
||||
config = py.test.config._reparse([str(tmpdir)])
|
||||
hosts = [HostInfo(i) for i in ["host1", "host2", "host3"]]
|
||||
for host in hosts:
|
||||
host.gw_remotepath = ''
|
||||
r = self.reporter(config, hosts)
|
||||
r.report(repevent.TestStarted(hosts, config, ["a", "b", "c"]))
|
||||
for host in hosts:
|
||||
r.report(repevent.HostGatewayReady(host, ["a", "b", "c"]))
|
||||
for host in hosts:
|
||||
for root in ["a", "b", "c"]:
|
||||
r.report(repevent.HostRSyncRootReady(host, root))
|
||||
out, err = cap.reset()
|
||||
assert not err
|
||||
expected1 = "Test started, hosts: host1[0], host2[0], host3[0]"
|
||||
assert out.find(expected1) != -1
|
||||
for expected in py.code.Source("""
|
||||
host1[0]: READY (still 2 to go)
|
||||
host2[0]: READY (still 1 to go)
|
||||
host3[0]: READY
|
||||
""").lines:
|
||||
expected = expected.strip()
|
||||
assert out.find(expected) != -1
|
||||
|
||||
class TestLocalReporter(AbstractTestReporter):
|
||||
reporter = LocalReporter
|
||||
|
||||
def get_hosts(self):
|
||||
return None
|
||||
|
||||
def test_report_received_item_outcome(self):
|
||||
assert self.report_received_item_outcome() == 'FsF.'
|
||||
|
||||
def test_verbose(self):
|
||||
self._test_verbose()
|
||||
|
||||
def test_module(self):
|
||||
output = self._test_module()
|
||||
assert output.find("test_one") != -1
|
||||
assert output.endswith("FsF."), output
|
||||
|
||||
def test_full_module(self):
|
||||
received = self._test_full_module()
|
||||
expected_lst = ["repmod/test_one.py", "FAILED TO LOAD MODULE",
|
||||
"skipped", "reason"]
|
||||
for i in expected_lst:
|
||||
assert received.find(i) != -1
|
||||
|
||||
class TestRemoteReporter(AbstractTestReporter):
|
||||
reporter = RemoteReporter
|
||||
|
||||
def get_hosts(self):
|
||||
return [HostInfo("host")]
|
||||
|
||||
def test_still_to_go(self):
|
||||
self._test_still_to_go()
|
||||
|
||||
def test_report_received_item_outcome(self):
|
||||
val = self.report_received_item_outcome()
|
||||
expected_lst = ["host", "FAILED",
|
||||
"funcpass", "test_one",
|
||||
"SKIPPED",
|
||||
"PASSED"]
|
||||
for expected in expected_lst:
|
||||
assert val.find(expected) != -1
|
||||
|
||||
def test_module(self):
|
||||
val = self._test_module()
|
||||
expected_lst = ["host", "FAILED",
|
||||
"funcpass", "test_one",
|
||||
"SKIPPED",
|
||||
"PASSED"]
|
||||
for expected in expected_lst:
|
||||
assert val.find(expected) != -1
|
||||
|
||||
def test_full_module(self):
|
||||
val = self._test_full_module()
|
||||
assert val.find("FAILED TO LOAD MODULE: repmod/test_three.py\n"\
|
||||
"\nSkipped ('reason') repmod/test_two.py") != -1
|
||||
|
||||
def test_reporter_choice():
|
||||
from py.__.test.rsession.web import WebReporter
|
||||
from py.__.test.rsession.rest import RestReporter
|
||||
choices = [
|
||||
(['-d', '--rest'], RestReporter),
|
||||
(['-w'], WebReporter),
|
||||
(['-r'], WebReporter)]
|
||||
for opts, reporter in choices:
|
||||
config = py.test.config._reparse(['xxx'] + opts)
|
||||
assert choose_reporter(None, config) is reporter
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
|
||||
import py
|
||||
from py.__.test.representation import Presenter
|
||||
from py.__.test.terminal.out import getout
|
||||
from StringIO import StringIO
|
||||
import sys
|
||||
|
||||
def newconfig(*args):
|
||||
tmpdir = py.test.ensuretemp("newconfig")
|
||||
args = list(args)
|
||||
args.append(tmpdir)
|
||||
return py.test.config._reparse(args)
|
||||
|
||||
def test_repr_source():
|
||||
source = py.code.Source("""
|
||||
def f(x):
|
||||
pass
|
||||
""").strip()
|
||||
config = newconfig()
|
||||
s = StringIO()
|
||||
out = getout(s)
|
||||
p = Presenter(out, config)
|
||||
p.repr_source(source, "|", 0)
|
||||
lines = s.getvalue().split("\n")
|
||||
assert len(lines) == 3
|
||||
assert lines[0].startswith("|")
|
||||
assert lines[0].find("def f(x)") != -1
|
||||
assert lines[1].find("pass") != -1
|
||||
|
||||
def test_repr_failure_explanation():
|
||||
""" We check here if indentation is right
|
||||
"""
|
||||
def f():
|
||||
def g():
|
||||
1/0
|
||||
try:
|
||||
g()
|
||||
except:
|
||||
e = py.code.ExceptionInfo()
|
||||
return e
|
||||
config = newconfig()
|
||||
s = StringIO()
|
||||
out = getout(s)
|
||||
p = Presenter(out, config)
|
||||
source = py.code.Source(f)
|
||||
e = f()
|
||||
p.repr_failure_explanation(e, source)
|
||||
assert s.getvalue().startswith("> ")
|
||||
|
||||
def test_repr_local():
|
||||
config = newconfig('--showlocals')
|
||||
s = StringIO()
|
||||
out = getout(s)
|
||||
p = Presenter(out, config)
|
||||
p.repr_locals(locals())
|
||||
for key in locals().keys():
|
||||
assert s.getvalue().find(key) != -1
|
||||
|
||||
def XXXtest_repr_traceback_long():
|
||||
py.test.skip("unfinished")
|
||||
config = py.test.config._reparse([])
|
||||
s = StringIO()
|
||||
out = getout(s)
|
||||
p = Presenter(out, config)
|
||||
# errr... here we should
|
||||
# a) prepare an item
|
||||
# b) prepare excinfo
|
||||
# c) prepare some traceback info, with few different ideas,
|
||||
# like recursion detected etc.
|
||||
# test it...
|
||||
@@ -1,299 +0,0 @@
|
||||
import py
|
||||
from setupdata import setup_module # sets up global 'tmpdir'
|
||||
from py.__.test.outcome import Skipped, Failed, Passed, Outcome
|
||||
from py.__.test.terminal.out import getout
|
||||
from py.__.test.repevent import ReceivedItemOutcome, SkippedTryiter,\
|
||||
FailedTryiter
|
||||
|
||||
implied_options = {
|
||||
'-v': 'verbose',
|
||||
'-l': 'showlocals',
|
||||
#'--runbrowser': 'startserver and runbrowser', XXX starts browser
|
||||
}
|
||||
|
||||
conflict_options = ('--looponfailing --pdb',
|
||||
'--dist --pdb',
|
||||
'--exec=%s --pdb' % py.std.sys.executable,
|
||||
)
|
||||
|
||||
def getoutcomes(all):
|
||||
return [i.outcome for i in all if isinstance(i, ReceivedItemOutcome)]
|
||||
|
||||
|
||||
def getpassed(all):
|
||||
return [i for i in getoutcomes(all) if i.passed]
|
||||
|
||||
def getskipped(all):
|
||||
return [i for i in getoutcomes(all) if i.skipped] + \
|
||||
[i for i in all if isinstance(i, SkippedTryiter)]
|
||||
|
||||
def getfailed(all):
|
||||
return [i for i in getoutcomes(all) if i.excinfo] + \
|
||||
[i for i in all if isinstance(i, FailedTryiter)]
|
||||
|
||||
def test_conflict_options():
|
||||
for spec in conflict_options:
|
||||
opts = spec.split()
|
||||
yield check_conflict_option, opts
|
||||
|
||||
def check_conflict_option(opts):
|
||||
print "testing if options conflict:", " ".join(opts)
|
||||
config = py.test.config._reparse(opts + [datadir/'filetest.py'])
|
||||
py.test.raises((ValueError, SystemExit), """
|
||||
config.initsession()
|
||||
""")
|
||||
|
||||
def test_implied_options():
|
||||
for key, expr in implied_options.items():
|
||||
yield check_implied_option, [key], expr
|
||||
|
||||
def check_implied_option(opts, expr):
|
||||
config = py.test.config._reparse(opts + [datadir/'filetest.py'])
|
||||
session = config.initsession()
|
||||
assert eval(expr, session.config.option.__dict__)
|
||||
|
||||
def test_default_session_options():
|
||||
for opts in ([], ['-l'], ['-s'], ['--tb=no'], ['--tb=short'],
|
||||
['--tb=long'], ['--fulltrace'], ['--nomagic'],
|
||||
['--traceconfig'], ['-v'], ['-v', '-v']):
|
||||
yield runfiletest, opts
|
||||
|
||||
def runfiletest(opts):
|
||||
config = py.test.config._reparse(opts + [datadir/'filetest.py'])
|
||||
all = []
|
||||
session = config.initsession()
|
||||
session.main(all.append)
|
||||
assert len(getfailed(all)) == 2
|
||||
assert not getskipped(all)
|
||||
|
||||
def test_is_not_boxed_by_default():
|
||||
config = py.test.config._reparse([datadir])
|
||||
assert not config.option.boxed
|
||||
|
||||
class TestKeywordSelection:
|
||||
def test_select_simple(self):
|
||||
def check(keyword, name):
|
||||
config = py.test.config._reparse([datadir/'filetest.py',
|
||||
'-s', '-k', keyword])
|
||||
all = []
|
||||
session = config._getsessionclass()(config)
|
||||
session.main(all.append)
|
||||
outcomes = [i for i in all if isinstance(i, ReceivedItemOutcome)]
|
||||
assert len(getfailed(all)) == 1
|
||||
assert outcomes[0].item.name == name
|
||||
l = getskipped(all)
|
||||
assert len(l) == 1
|
||||
|
||||
for keyword in ['test_one', 'est_on']:
|
||||
check(keyword, 'test_one')
|
||||
check('TestClass.test', 'test_method_one')
|
||||
|
||||
def test_select_extra_keywords(self):
|
||||
o = tmpdir.ensure('selecttest', dir=1)
|
||||
tfile = o.join('test_select.py').write(py.code.Source("""
|
||||
def test_1():
|
||||
pass
|
||||
class TestClass:
|
||||
def test_2(self):
|
||||
pass
|
||||
"""))
|
||||
conftest = o.join('conftest.py').write(py.code.Source("""
|
||||
import py
|
||||
class Class(py.test.collect.Class):
|
||||
def _keywords(self):
|
||||
return ['xxx', self.name]
|
||||
"""))
|
||||
for keyword in ('xxx', 'xxx test_2', 'TestClass', 'xxx -test_1',
|
||||
'TestClass test_2', 'xxx TestClass test_2',):
|
||||
config = py.test.config._reparse([o, '-s', '-k', keyword])
|
||||
all = []
|
||||
session = config._getsessionclass()(config)
|
||||
session.main(all.append)
|
||||
print "keyword", repr(keyword)
|
||||
l = getpassed(all)
|
||||
outcomes = [i for i in all if isinstance(i, ReceivedItemOutcome)]
|
||||
assert len(l) == 1
|
||||
assert outcomes[0].item.name == 'test_2'
|
||||
l = getskipped(all)
|
||||
assert l[0].item.name == 'test_1'
|
||||
|
||||
def test_select_starton(self):
|
||||
config = py.test.config._reparse([datadir/'testevenmore.py',
|
||||
'-j', '-k', "test_three"])
|
||||
all = []
|
||||
session = config._getsessionclass()(config)
|
||||
session.main(all.append)
|
||||
assert len(getpassed(all)) == 2
|
||||
assert len(getskipped(all)) == 2
|
||||
|
||||
|
||||
class TestTerminalSession:
|
||||
def mainsession(self, *args):
|
||||
from py.__.test.session import Session
|
||||
from py.__.test.terminal.out import getout
|
||||
config = py.test.config._reparse(list(args))
|
||||
all = []
|
||||
session = Session(config)
|
||||
session.main(all.append)
|
||||
return session, all
|
||||
|
||||
def test_terminal(self):
|
||||
session, all = self.mainsession(datadir / 'filetest.py')
|
||||
outcomes = getoutcomes(all)
|
||||
assert len(getfailed(all)) == 2
|
||||
|
||||
def test_syntax_error_module(self):
|
||||
session, all = self.mainsession(datadir / 'syntax_error.py')
|
||||
l = getfailed(all)
|
||||
assert len(l) == 1
|
||||
out = l[0].excinfo.exconly()
|
||||
assert out.find(str('syntax_error.py')) != -1
|
||||
assert out.find(str('not python')) != -1
|
||||
|
||||
def test_exit_first_problem(self):
|
||||
session, all = self.mainsession("--exitfirst",
|
||||
datadir / 'filetest.py')
|
||||
assert session.config.option.exitfirst
|
||||
assert len(getfailed(all)) == 1
|
||||
assert not getpassed(all)
|
||||
|
||||
def test_generator_yields_None(self):
|
||||
o = tmpdir.ensure('generatornonetest', dir=1)
|
||||
tfile = o.join('test_generatornone.py')
|
||||
tfile.write(py.code.Source("""
|
||||
def test_1():
|
||||
yield None
|
||||
"""))
|
||||
session, all = self.mainsession(o)
|
||||
#print out
|
||||
failures = getfailed(all)
|
||||
out = failures[0].excinfo.exconly()
|
||||
i = out.find('TypeError')
|
||||
assert i != -1
|
||||
|
||||
def test_capturing_hooks_simple(self):
|
||||
o = tmpdir.ensure('capturing', dir=1)
|
||||
tfile = o.join('test_capturing.py').write(py.code.Source("""
|
||||
import py
|
||||
print "module level output"
|
||||
def test_capturing():
|
||||
print 42
|
||||
print >>py.std.sys.stderr, 23
|
||||
def test_capturing_error():
|
||||
print 1
|
||||
print >>py.std.sys.stderr, 2
|
||||
raise ValueError
|
||||
"""))
|
||||
conftest = o.join('conftest.py').write(py.code.Source("""
|
||||
import py
|
||||
class Function(py.test.collect.Function):
|
||||
def startcapture(self):
|
||||
self._mycapture = None
|
||||
|
||||
def finishcapture(self):
|
||||
self._testmycapture = None
|
||||
"""))
|
||||
session, all = self.mainsession(o)
|
||||
l = getpassed(all)
|
||||
outcomes = getoutcomes(all)
|
||||
assert len(l) == 1
|
||||
item = all[3].item # item is not attached to outcome, but it's the
|
||||
# started before
|
||||
assert hasattr(item, '_testmycapture')
|
||||
print item._testmycapture
|
||||
|
||||
assert isinstance(item.parent, py.test.collect.Module)
|
||||
|
||||
def test_raises_output(self):
|
||||
o = tmpdir.ensure('raisestest', dir=1)
|
||||
tfile = o.join('test_raisesoutput.py')
|
||||
tfile.write(py.code.Source("""
|
||||
import py
|
||||
def test_raises_doesnt():
|
||||
py.test.raises(ValueError, int, "3")
|
||||
"""))
|
||||
session, all = self.mainsession(o)
|
||||
outcomes = getoutcomes(all)
|
||||
out = outcomes[0].excinfo.exconly()
|
||||
if not out.find("DID NOT RAISE") != -1:
|
||||
print out
|
||||
py.test.fail("incorrect raises() output")
|
||||
|
||||
def test_order_of_execution(self):
|
||||
o = tmpdir.ensure('ordertest', dir=1)
|
||||
tfile = o.join('test_orderofexecution.py')
|
||||
tfile.write(py.code.Source("""
|
||||
l = []
|
||||
def test_1():
|
||||
l.append(1)
|
||||
def test_2():
|
||||
l.append(2)
|
||||
def test_3():
|
||||
assert l == [1,2]
|
||||
class Testmygroup:
|
||||
reslist = l
|
||||
def test_1(self):
|
||||
self.reslist.append(1)
|
||||
def test_2(self):
|
||||
self.reslist.append(2)
|
||||
def test_3(self):
|
||||
self.reslist.append(3)
|
||||
def test_4(self):
|
||||
assert self.reslist == [1,2,1,2,3]
|
||||
"""))
|
||||
|
||||
session, all = self.mainsession(o)
|
||||
assert len(getfailed(all)) == 0
|
||||
assert len(getpassed(all)) == 7
|
||||
# also test listnames() here ...
|
||||
|
||||
def test_nested_import_error(self):
|
||||
o = tmpdir.ensure('Ians_importfailure', dir=1)
|
||||
tfile = o.join('test_import_fail.py')
|
||||
tfile.write(py.code.Source("""
|
||||
import import_fails
|
||||
def test_this():
|
||||
assert import_fails.a == 1
|
||||
"""))
|
||||
o.join('import_fails.py').write(py.code.Source("""
|
||||
import does_not_work
|
||||
a = 1
|
||||
"""))
|
||||
session, all = self.mainsession(o)
|
||||
l = getfailed(all)
|
||||
assert len(l) == 1
|
||||
out = l[0].excinfo.exconly()
|
||||
assert out.find('does_not_work') != -1
|
||||
|
||||
def test_safe_repr(self):
|
||||
session, all = self.mainsession(datadir/'brokenrepr.py')
|
||||
#print 'Output of simulated "py.test brokenrepr.py":'
|
||||
#print all
|
||||
|
||||
l = getfailed(all)
|
||||
assert len(l) == 2
|
||||
out = l[0].excinfo.exconly()
|
||||
assert out.find("""[Exception("Ha Ha fooled you, I'm a broken repr().") raised in repr()]""") != -1 #'
|
||||
out = l[1].excinfo.exconly()
|
||||
assert out.find("[unknown exception raised in repr()]") != -1
|
||||
|
||||
def test_skip_reasons():
|
||||
tmp = py.test.ensuretemp("check_skip_reasons")
|
||||
tmp.ensure("test_one.py").write(py.code.Source("""
|
||||
import py
|
||||
def test_1():
|
||||
py.test.skip("Broken: stuff")
|
||||
|
||||
def test_2():
|
||||
py.test.skip("Not implemented: stuff")
|
||||
"""))
|
||||
tmp.ensure("__init__.py")
|
||||
config = py.test.config._reparse([tmp])
|
||||
all = []
|
||||
session = config.initsession()
|
||||
session.main(all.append)
|
||||
skips = getskipped(all)
|
||||
assert len(skips) == 2
|
||||
assert str(skips[0].skipped.value).find('Broken: stuff') != -1
|
||||
assert str(skips[1].skipped.value).find('Not implemented: stuff') != -1
|
||||
|
||||
@@ -1,287 +0,0 @@
|
||||
|
||||
""" test of local version of py.test distributed
|
||||
"""
|
||||
|
||||
import py
|
||||
from py.__.test import repevent
|
||||
#from py.__.test.rsession.local import box_runner, plain_runner, apigen_runner
|
||||
import py.__.test.custompdb
|
||||
from py.__.test.session import Session
|
||||
|
||||
def setup_module(mod):
|
||||
mod.tmp = py.test.ensuretemp("lsession_module")
|
||||
|
||||
class TestSession(object):
|
||||
# XXX: Some tests of that should be run as well on RSession, while
|
||||
# some not at all
|
||||
def example_distribution(self, boxed=False):
|
||||
# XXX find a better way for the below
|
||||
tmpdir = tmp
|
||||
dirname = "sub_lsession"#+runner.func_name
|
||||
tmpdir.ensure(dirname, "__init__.py")
|
||||
tmpdir.ensure(dirname, "test_one.py").write(py.code.Source("""
|
||||
def test_1():
|
||||
pass
|
||||
def test_2():
|
||||
assert 0
|
||||
def test_3():
|
||||
raise ValueError(23)
|
||||
def test_4(someargs):
|
||||
pass
|
||||
#def test_5():
|
||||
# import os
|
||||
# os.kill(os.getpid(), 11)
|
||||
"""))
|
||||
args = [str(tmpdir.join(dirname))]
|
||||
if boxed:
|
||||
args.append('--boxed')
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
lsession.main(reporter=allevents.append)
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
assert len(testevents)
|
||||
passevents = [i for i in testevents if i.outcome.passed]
|
||||
failevents = [i for i in testevents if i.outcome.excinfo]
|
||||
skippedevents = [i for i in testevents if i.outcome.skipped]
|
||||
signalevents = [i for i in testevents if i.outcome.signal]
|
||||
assert len(passevents) == 1
|
||||
assert len(failevents) == 3
|
||||
assert len(skippedevents) == 0
|
||||
#assert len(signalevents) == 1
|
||||
tb = failevents[0].outcome.excinfo.traceback
|
||||
assert str(tb[0].path).find("test_one") != -1
|
||||
assert str(tb[0].source).find("test_2") != -1
|
||||
assert failevents[0].outcome.excinfo.typename == 'AssertionError'
|
||||
tb = failevents[1].outcome.excinfo.traceback
|
||||
assert str(tb[0].path).find("test_one") != -1
|
||||
assert str(tb[0].source).find("test_3") != -1
|
||||
assert failevents[1].outcome.excinfo.typename == 'ValueError'
|
||||
assert str(failevents[1].outcome.excinfo.value) == '23'
|
||||
tb = failevents[2].outcome.excinfo.traceback
|
||||
assert failevents[2].outcome.excinfo.typename == 'TypeError'
|
||||
assert str(tb[0].path).find("executor") != -1
|
||||
assert str(tb[0].source).find("execute") != -1
|
||||
|
||||
def test_boxed(self):
|
||||
if not hasattr(py.std.os, 'fork'):
|
||||
py.test.skip('operating system not supported')
|
||||
self.example_distribution(True)
|
||||
|
||||
def test_box_exploding(self):
|
||||
if not hasattr(py.std.os, 'fork'):
|
||||
py.test.skip('operating system not supported')
|
||||
tmpdir = tmp
|
||||
dirname = "boxtest"
|
||||
tmpdir.ensure(dirname, "__init__.py")
|
||||
tmpdir.ensure(dirname, "test_one.py").write(py.code.Source("""
|
||||
def test_5():
|
||||
import os
|
||||
os.kill(os.getpid(), 11)
|
||||
"""))
|
||||
args = [str(tmpdir.join(dirname))]
|
||||
args.append('--boxed')
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
lsession.main(reporter=allevents.append)
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
assert len(testevents)
|
||||
assert testevents[0].outcome.signal
|
||||
|
||||
def test_plain(self):
|
||||
self.example_distribution(False)
|
||||
|
||||
def test_pdb_run(self):
|
||||
# we make sure that pdb is engaged
|
||||
tmpdir = tmp
|
||||
subdir = "sub_pdb_run"
|
||||
tmpdir.ensure(subdir, "__init__.py")
|
||||
tmpdir.ensure(subdir, "test_one.py").write(py.code.Source("""
|
||||
def test_1():
|
||||
assert 0
|
||||
"""))
|
||||
l = []
|
||||
def some_fun(*args):
|
||||
l.append(args)
|
||||
|
||||
try:
|
||||
post_mortem = py.__.test.custompdb.post_mortem
|
||||
py.__.test.custompdb.post_mortem = some_fun
|
||||
args = [str(tmpdir.join(subdir)), '--pdb']
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
#try:
|
||||
lsession.main(reporter=allevents.append)
|
||||
#except SystemExit:
|
||||
# pass
|
||||
#else:
|
||||
# py.test.fail("Didn't raise system exit")
|
||||
failure_events = [event for event in allevents if isinstance(event,
|
||||
repevent.ImmediateFailure)]
|
||||
assert len(failure_events) == 1
|
||||
assert len(l) == 1
|
||||
finally:
|
||||
py.__.test.custompdb.post_mortem = post_mortem
|
||||
|
||||
def test_minus_x(self):
|
||||
if not hasattr(py.std.os, 'fork'):
|
||||
py.test.skip('operating system not supported')
|
||||
tmpdir = tmp
|
||||
subdir = "sub_lsession_minus_x"
|
||||
tmpdir.ensure(subdir, "__init__.py")
|
||||
tmpdir.ensure(subdir, "test_one.py").write(py.code.Source("""
|
||||
def test_1():
|
||||
pass
|
||||
def test_2():
|
||||
assert 0
|
||||
def test_3():
|
||||
raise ValueError(23)
|
||||
def test_4(someargs):
|
||||
pass
|
||||
"""))
|
||||
args = [str(tmpdir.join(subdir)), '-x']
|
||||
config = py.test.config._reparse(args)
|
||||
assert config.option.exitfirst
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
|
||||
lsession.main(reporter=allevents.append)
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
assert len(testevents)
|
||||
passevents = [i for i in testevents if i.outcome.passed]
|
||||
failevents = [i for i in testevents if i.outcome.excinfo]
|
||||
assert len(passevents) == 1
|
||||
assert len(failevents) == 1
|
||||
|
||||
def test_minus_k(self):
|
||||
if not hasattr(py.std.os, 'fork'):
|
||||
py.test.skip('operating system not supported')
|
||||
tmpdir = tmp
|
||||
tmpdir.ensure("sub3", "__init__.py")
|
||||
tmpdir.ensure("sub3", "test_some.py").write(py.code.Source("""
|
||||
def test_one():
|
||||
pass
|
||||
def test_one_one():
|
||||
assert 0
|
||||
def test_other():
|
||||
raise ValueError(23)
|
||||
def test_two(someargs):
|
||||
pass
|
||||
"""))
|
||||
args = [str(tmpdir.join("sub3")), '-k', 'test_one']
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
|
||||
lsession.main(reporter=allevents.append)
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
assert len(testevents)
|
||||
passevents = [i for i in testevents if i.outcome.passed]
|
||||
failevents = [i for i in testevents if i.outcome.excinfo]
|
||||
assert len(passevents) == 1
|
||||
assert len(failevents) == 1
|
||||
|
||||
def test_lsession(self):
|
||||
tmpdir = tmp
|
||||
tmpdir.ensure("sub4", "__init__.py")
|
||||
tmpdir.ensure("sub4", "test_some.py").write(py.code.Source("""
|
||||
def test_one():
|
||||
pass
|
||||
def test_one_one():
|
||||
assert 0
|
||||
def test_other():
|
||||
raise ValueError(23)
|
||||
def test_two(someargs):
|
||||
pass
|
||||
"""))
|
||||
|
||||
args = [str(tmpdir.join("sub4"))]
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
allruns = []
|
||||
lsession.main(reporter=allevents.append)
|
||||
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
assert len(testevents) == 4
|
||||
lst = ['test_one', 'test_one_one', 'test_other', 'test_two']
|
||||
for num, i in enumerate(testevents):
|
||||
#assert i.item == i.outcome
|
||||
assert i.item.name == lst[num]
|
||||
|
||||
def test_module_raising(self):
|
||||
tmpdir = tmp
|
||||
tmpdir.ensure("sub5", "__init__.py")
|
||||
tmpdir.ensure("sub5", "test_some.py").write(py.code.Source("""
|
||||
1/0
|
||||
"""))
|
||||
tmpdir.ensure("sub5", "test_other.py").write(py.code.Source("""
|
||||
import py
|
||||
py.test.skip("reason")
|
||||
"""))
|
||||
|
||||
args = [str(tmpdir.join("sub5"))]
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
lsession.main(reporter=allevents.append)
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
assert len(testevents) == 0
|
||||
failedtryiter = [x for x in allevents
|
||||
if isinstance(x, repevent.FailedTryiter)]
|
||||
assert len(failedtryiter) == 1
|
||||
skippedtryiter = [x for x in allevents
|
||||
if isinstance(x, repevent.SkippedTryiter)]
|
||||
assert len(skippedtryiter) == 1
|
||||
|
||||
|
||||
def test_assert_reinterpret(self):
|
||||
if not hasattr(py.std.os, 'fork'):
|
||||
py.test.skip('operating system not supported')
|
||||
tmpdir = tmp
|
||||
tmpdir.ensure("sub6", "__init__.py")
|
||||
tmpdir.ensure("sub6", "test_some.py").write(py.code.Source("""
|
||||
def test_one():
|
||||
x = [1, 2]
|
||||
assert [0] == x
|
||||
"""))
|
||||
args = [str(tmpdir.join("sub6"))]
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
lsession.main(reporter=allevents.append)
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
failevents = [i for i in testevents if i.outcome.excinfo]
|
||||
assert len(failevents) == 1
|
||||
assert len(testevents) == 1
|
||||
assert failevents[0].outcome.excinfo.value == 'assert [0] == [1, 2]'
|
||||
|
||||
def test_nocapture(self):
|
||||
tmpdir = tmp
|
||||
tmpdir.ensure("sub7", "__init__.py")
|
||||
tmpdir.ensure("sub7", "test_nocap.py").write(py.code.Source("""
|
||||
def test_one():
|
||||
print 1
|
||||
print 2
|
||||
print 3
|
||||
"""))
|
||||
args = [str(tmpdir.join("sub7"))]
|
||||
config = py.test.config._reparse(args)
|
||||
lsession = Session(config)
|
||||
allevents = []
|
||||
lsession.main(reporter=allevents.append)
|
||||
testevents = [x for x in allevents
|
||||
if isinstance(x, repevent.ReceivedItemOutcome)]
|
||||
assert len(testevents) == 1
|
||||
assert testevents[0].outcome.passed
|
||||
assert testevents[0].outcome.stderr == ""
|
||||
assert testevents[0].outcome.stdout == "1\n2\n3\n"
|
||||
@@ -1,64 +0,0 @@
|
||||
|
||||
#
|
||||
# test correct setup/teardowns at
|
||||
# module, class, and instance level
|
||||
|
||||
modlevel = []
|
||||
def setup_module(module):
|
||||
assert not modlevel
|
||||
module.modlevel.append(42)
|
||||
|
||||
def teardown_module(module):
|
||||
modlevel.pop()
|
||||
|
||||
def setup_function(function):
|
||||
function.answer = 17
|
||||
|
||||
def teardown_function(function):
|
||||
del function.answer
|
||||
|
||||
def test_modlevel():
|
||||
assert modlevel[0] == 42
|
||||
assert test_modlevel.answer == 17
|
||||
|
||||
class TestSimpleClassSetup:
|
||||
clslevel = []
|
||||
def setup_class(cls):
|
||||
cls.clslevel.append(23)
|
||||
|
||||
def teardown_class(cls):
|
||||
cls.clslevel.pop()
|
||||
|
||||
def test_classlevel(self):
|
||||
assert self.clslevel[0] == 23
|
||||
|
||||
def test_modulelevel(self):
|
||||
print modlevel
|
||||
assert modlevel == [42]
|
||||
|
||||
class TestInheritedClassSetupStillWorks(TestSimpleClassSetup):
|
||||
def test_classlevel_anothertime(self):
|
||||
assert self.clslevel == [23]
|
||||
|
||||
class TestSetupTeardownOnInstance(TestSimpleClassSetup):
|
||||
def setup_method(self, method):
|
||||
self.clslevel.append(method.__name__)
|
||||
|
||||
def teardown_method(self, method):
|
||||
x = self.clslevel.pop()
|
||||
assert x == method.__name__
|
||||
|
||||
def test_setup(self):
|
||||
assert self.clslevel[-1] == 'test_setup'
|
||||
|
||||
def test_generate(self):
|
||||
assert self.clslevel[-1] == 'test_generate'
|
||||
yield self.generated, 5
|
||||
assert self.clslevel[-1] == 'test_generate'
|
||||
|
||||
def generated(self, value):
|
||||
assert value == 5
|
||||
assert self.clslevel[-1] == 'test_generate'
|
||||
|
||||
def test_teardown_method_worked():
|
||||
assert not TestSetupTeardownOnInstance.clslevel
|
||||
Reference in New Issue
Block a user