Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to py.test #151

Merged
merged 47 commits into from
May 22, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
4a587df
Ignore all types of virtualenv dir
tony May 21, 2016
ace8043
Refactor tests structure for py.test, optimize helper imports
tony May 21, 2016
553ac81
Ignore .cache/ and .eggs/
tony May 21, 2016
dfa1cb1
switch window rename to use sh shell as test
tony May 21, 2016
8c18356
Add flaky for rerunning those tricky testcases
tony May 21, 2016
bd6616a
reorder test deps
tony May 21, 2016
82ed172
Update pip, wheel, virtualenv before install on travis
tony May 21, 2016
79b981b
Try upgrading setuptools
tony May 21, 2016
06779a1
Upgrade pytest
tony May 21, 2016
20b3fd1
try upgrading setuptools/pip once more
tony May 21, 2016
9bfd122
Omit tests/ dir from coveragerc
tony May 21, 2016
8f380b6
remove run-tests.py
tony May 21, 2016
a06bc09
Update make test command to py.test
tony May 21, 2016
2c467b3
Clean up old TestLoader infrastructure
tony May 21, 2016
03df8df
flake8 for tests also
tony May 21, 2016
bd7e8f9
Refactor tests for py.test fixture, polish
tony May 21, 2016
d416a53
Update docs for new test directions
tony May 21, 2016
bebbd88
Update README/dox/MANIFEST.in to rm run-tests.py and use make test
tony May 21, 2016
120106c
switch to py.test style asserts, cleanup param order
tony May 21, 2016
713a5e8
port cli tests to py.test functions
tony May 21, 2016
43b4973
midway commit of py.test function rewrite test_config
tony May 22, 2016
e5abc75
Move second expansion test to yaml files+fixtures
tony May 22, 2016
2823379
add util to load fixtures, more tests to fixtures, py.test functions
tony May 22, 2016
41e89ed
move sample config to fixture
tony May 22, 2016
9314c5c
helper function to make loading configs brief
tony May 22, 2016
d9b1de0
Finish test_config py.test fixturization/function conversion
tony May 22, 2016
fcd54c3
Briefen fixture name
tony May 22, 2016
8cbeac7
Move load fixtures to tests/fixtures root
tony May 22, 2016
3141d81
teamocil config tests to fixtures
tony May 22, 2016
e788ab5
Move rest of tmuxinator configs to fixtures
tony May 22, 2016
9f8adcb
move tests for test helpers to tests/tests/
tony May 22, 2016
4316aa0
convert window test to functional, add server/session test fixtures
tony May 22, 2016
10b8eb8
parametrize multisession teamocil import test
tony May 22, 2016
795df2e
Move rest of teamocil config tests to py.test
tony May 22, 2016
781129b
tmuxinator tests to py.test parametrized funcs
tony May 22, 2016
faa771a
Rename t decorator to server, test_server to py.test funcs
tony May 22, 2016
66a9493
move test_session to py.test funcs
tony May 22, 2016
b9eb738
port test_tmuxobject to py.test
tony May 22, 2016
f877bae
workspace{builder,freeze} split fixtures, tweak flaky
tony May 22, 2016
7df1b3c
move more tests (util, workspacebuilder) to py.test func
tony May 22, 2016
8225be1
convert rest tests to py.test
tony May 22, 2016
e7b0591
Clean out unused test helpers, fixture usage fixes
tony May 22, 2016
310ebcc
remove unittest2 dep
tony May 22, 2016
586456b
Fix indentation in setup.py
tony May 22, 2016
447f917
fixes to test decorators, run in function scope for now
tony May 22, 2016
91ccb36
rm unittest2 dep from tox
tony May 22, 2016
2fab3a0
Update doc for pytest
tony May 22, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Clean out unused test helpers, fixture usage fixes
  • Loading branch information
tony committed May 22, 2016
commit e7b0591e54e5749fbf8a515d9e84a450cd6935c1
7 changes: 0 additions & 7 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,3 @@
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals, with_statement)

import sys

if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest # NOQA
262 changes: 1 addition & 261 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""Helper methods for tmuxp unittests.
"""Helper methods for tmuxp tests.

_CallableContext, WhateverIO, decorator and stdouts are from the case project,
https://github.com/celery/case, license BSD 3-clause.
Expand All @@ -9,22 +9,9 @@
unicode_literals, with_statement)

import contextlib
import functools
import inspect
import io
import logging
import os
import sys
import tempfile
from contextlib import contextmanager

from tmuxp import exc
from tmuxp.server import Server

if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -125,253 +112,6 @@ def temp_window(session, *args, **kwargs):
return


class TestCase(unittest.TestCase):

"""Base TestClass so we don't have to try: unittest2 every module. """

@classmethod
def setUpClass(cls):
super(TestCase, cls).setUpClass() # for python 2.6 unittest2


class TmuxTestCase(TestCase):

"""TmuxTestCase class, wraps the TestCase in a :class:`Session`."""

#: :class:`Session` object.
session = None
#: Session name for the TestCase.
TEST_SESSION_NAME = None

def temp_session(self, session_name=None):
return temp_session(self.server, session_name)

def setUp(self):
"""Run bootstrap if :attr:`~.session` is not set."""

if not self.TEST_SESSION_NAME or not self.session:
self.bootstrap()

def bootstrap(self):
"""Return tuple of the session_name (generated) and :class:`Session`.

Checks to verify if the user has a tmux client open.

It will clean up and delete other sessions starting with the
:attr:`TEST_SESSION_PREFIX` ``tmuxp``.

Since tmux closes when all sessions are deleted, the bootstrap will see
if there is no other client open aside from a tmuxp_ prefixed session
a dumby session will be made to prevent tmux from closing.

"""
self.t = t = Server()
t.socket_name = 'tmuxp_test'

session_name = 'tmuxp'
if not t.has_session(session_name):
t.cmd('new-session', '-d', '-s', session_name)

# find current sessions prefixed with tmuxp
old_test_sessions = [
s.get('session_name') for s in t._sessions
if s.get('session_name').startswith(TEST_SESSION_PREFIX)
]

TEST_SESSION_NAME = get_test_session_name(server=t)

try:
session = t.new_session(
session_name=TEST_SESSION_NAME,
)
except exc.TmuxpException as e:
raise e

"""
Make sure that tmuxp can :ref:`test_builder_visually` and switches to
the newly created session for that testcase.
"""
try:
t.switch_client(session.get('session_id'))
pass
except exc.TmuxpException as e:
# t.attach_session(session.get('session_id'))
pass

for old_test_session in old_test_sessions:
logger.debug(
'Old test test session %s found. Killing it.' %
old_test_session
)
t.kill_session(old_test_session)
assert TEST_SESSION_NAME == session.get('session_name')
assert TEST_SESSION_NAME != 'tmuxp'

self.TEST_SESSION_NAME = TEST_SESSION_NAME
self.server = t
self.session = session


StringIO = io.StringIO
_SIO_write = StringIO.write
_SIO_init = StringIO.__init__


def update_wrapper(wrapper, wrapped, *args, **kwargs):
wrapper = functools.update_wrapper(wrapper, wrapped, *args, **kwargs)
wrapper.__wrapped__ = wrapped
return wrapper


def wraps(wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
return functools.partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)


class _CallableContext(object):

def __init__(self, context, cargs, ckwargs, fun):
self.context = context
self.cargs = cargs
self.ckwargs = ckwargs
self.fun = fun

def __call__(self, *args, **kwargs):
return self.fun(*args, **kwargs)

def __enter__(self):
self.ctx = self.context(*self.cargs, **self.ckwargs)
return self.ctx.__enter__()

def __exit__(self, *einfo):
if self.ctx:
return self.ctx.__exit__(*einfo)


def decorator(predicate):
context = contextmanager(predicate)

@wraps(predicate)
def take_arguments(*pargs, **pkwargs):

@wraps(predicate)
def decorator(cls):
if inspect.isclass(cls):
orig_setup = cls.setUp
orig_teardown = cls.tearDown

@wraps(cls.setUp)
def around_setup(*args, **kwargs):
try:
contexts = args[0].__rb3dc_contexts__
except AttributeError:
contexts = args[0].__rb3dc_contexts__ = []
p = context(*pargs, **pkwargs)
p.__enter__()
contexts.append(p)
return orig_setup(*args, **kwargs)
around_setup.__wrapped__ = cls.setUp
cls.setUp = around_setup

@wraps(cls.tearDown)
def around_teardown(*args, **kwargs):
try:
contexts = args[0].__rb3dc_contexts__
except AttributeError:
pass
else:
for context in contexts:
context.__exit__(*sys.exc_info())
orig_teardown(*args, **kwargs)
around_teardown.__wrapped__ = cls.tearDown
cls.tearDown = around_teardown

return cls
else:
@wraps(cls)
def around_case(self, *args, **kwargs):
with context(*pargs, **pkwargs) as context_args:
context_args = context_args or ()
if not isinstance(context_args, tuple):
context_args = (context_args,)
return cls(*(self,) + args + context_args, **kwargs)
return around_case

if len(pargs) == 1 and callable(pargs[0]):
fun, pargs = pargs[0], ()
return decorator(fun)
return _CallableContext(context, pargs, pkwargs, decorator)
assert take_arguments.__wrapped__
return take_arguments


class WhateverIO(StringIO):

def __init__(self, v=None, *a, **kw):
_SIO_init(self, v.decode() if isinstance(v, bytes) else v, *a, **kw)

def write(self, data):
_SIO_write(self, data.decode() if isinstance(data, bytes) else data)


@decorator
def stdouts():
"""Override `sys.stdout` and `sys.stderr` with `StringIO`
instances.
Decorator example::
@mock.stdouts
def test_foo(self, stdout, stderr):
something()
self.assertIn('foo', stdout.getvalue())
Context example::
with mock.stdouts() as (stdout, stderr):
something()
self.assertIn('foo', stdout.getvalue())
"""
prev_out, prev_err = sys.stdout, sys.stderr
prev_rout, prev_rerr = sys.__stdout__, sys.__stderr__
mystdout, mystderr = WhateverIO(), WhateverIO()
sys.stdout = sys.__stdout__ = mystdout
sys.stderr = sys.__stderr__ = mystderr

try:
yield mystdout, mystderr
finally:
sys.stdout = prev_out
sys.stderr = prev_err
sys.__stdout__ = prev_rout
sys.__stderr__ = prev_rerr


@decorator
def mute():
"""Redirect `sys.stdout` and `sys.stderr` to /dev/null, silencent them.
Decorator example::
@mute
def test_foo(self):
something()
Context example::
with mute():
something()
"""
prev_out, prev_err = sys.stdout, sys.stderr
prev_rout, prev_rerr = sys.__stdout__, sys.__stderr__
devnull = open(os.devnull, 'w')
mystdout, mystderr = devnull, devnull
sys.stdout = sys.__stdout__ = mystdout
sys.stderr = sys.__stderr__ = mystderr

try:
yield
finally:
sys.stdout = prev_out
sys.stderr = prev_err
sys.__stdout__ = prev_rout
sys.__stderr__ = prev_rerr


class EnvironmentVarGuard(object):

"""Class to help protect the environment variable properly. Can be used as
Expand Down
12 changes: 6 additions & 6 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def test_has_session(server, session):
assert not server.has_session('asdf2314324321')


def test_socket_name():
def test_socket_name(server):
""" ``-L`` socket_name.

``-L`` socket_name file name of socket. which will be stored in
Expand All @@ -28,20 +28,20 @@ def test_socket_name():
assert myserver.socket_name == 'test'


def test_socket_path():
def test_socket_path(server):
""" ``-S`` socket_path (alternative path for server socket). """
myserver = Server(socket_path='test')

assert myserver.socket_path == 'test'


def test_config():
def test_config(server):
""" ``-f`` file for tmux(1) configuration. """
myserver = Server(config_file='test')
assert myserver.config_file == 'test'


def test_256_colors():
def test_256_colors(server):
myserver = Server(colors=256)
assert myserver.colors == 256

Expand All @@ -51,7 +51,7 @@ def test_256_colors():
assert '-8' not in proc.cmd


def test_88_colors():
def test_88_colors(server):
myserver = Server(colors=88)
assert myserver.colors == 88

Expand All @@ -67,7 +67,7 @@ def test_show_environment(server):
assert isinstance(_vars, dict)


def test_set_show_environment_single(server):
def test_set_show_environment_single(server, session):
"""Set environment then Server.show_environment(key)."""
server.set_environment('FOO', 'BAR')
assert 'BAR' == server.show_environment('FOO')
Expand Down
6 changes: 3 additions & 3 deletions tests/test_tmuxobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"""Test the :class:`TmuxRelationalObject` base class object."""


def test_findWhere(server):
def test_findWhere(server, session):
"""Test that findWhere() retrieves single matching object."""
# server.findWhere
for session in server.sessions:
Expand Down Expand Up @@ -44,7 +44,7 @@ def test_findWhere(server):
window.findWhere({'pane_id': pane_id}), Pane)


def test_findWhere_None(server):
def test_findWhere_None(server, session):
""".findWhere returns None if no results found."""

while True:
Expand All @@ -58,7 +58,7 @@ def test_findWhere_None(server):
}) is None


def test_findWhere_multiple_attrs(server):
def test_findWhere_multiple_attrs(server, session):
""".findWhere returns objects with multiple attributes."""

for session in server.sessions:
Expand Down
5 changes: 0 additions & 5 deletions tests/tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,3 @@ def test_if_session_killed_before(server):

# really dead?
assert not server.has_session(session_name)


def test_if_session_name_works(self):
"""should allow custom ``session_name``."""
pass