Exemplo n.º 1
0
        print(loaded)


def test_optional_in_list():
    @dataclass
    class __Simple:
        a: int
        b: int

    expected = [[{"a": 1, "b": 2}]]
    yml = yaml.safe_dump(expected)
    loaded = load(yml, List[List[Optional[__Simple]]])
    assert loaded == [[__Simple(1, 2)]]


skip_literal = mark.skipif(sys.version_info < (3, 9), reason="requires python 3.9+")


@skip_literal
def test_with_literal():
    from typing import Literal

    @dataclass
    class WithLiteral:
        default_section: Literal["one", "two", "unknown"] = "unknown"
        other: int = 0

    yml = """
default_section: one
"""
Exemplo n.º 2
0
from ethereum.tools import tester
import numpy as np
from os import getenv
from pytest import fixture, mark
from utils import fix, longTo32Bytes
from constants import BID, ASK

pytestmark = mark.skipif(not getenv('INCLUDE_FUZZY_TESTS'), reason="take forever to run")

ATTOSHARES = 0
DISPLAY_PRICE = 1
OWNER = 2
TOKENS_ESCROWED = 3
SHARES_ESCROWED = 4
BETTER_ORDER_ID = 5
WORSE_ORDER_ID = 6
GAS_PRICE = 7

@mark.parametrize('orderType,numOrders,withBoundingOrders,deadOrderProbability', [
    (BID,  10, False,  0.0),
    (ASK,  10, False,  0.0),
    (BID,  50, False,  0.0),
    (ASK,  50, False,  0.0),
    (BID, 100, False,  0.0),
    (ASK, 100, False,  0.0),

    (BID,  10, True,   0.0),
    (ASK,  10, True,   0.0),
    (BID,  50, True,   0.0),
    (ASK,  50, True,   0.0),
    (BID, 100, True,   0.0),
Exemplo n.º 3
0
import sys

import pytest
from pytest import mark

from osbrain import run_agent
from osbrain import run_logger
from osbrain import run_nameserver
from osbrain.helper import sync_agent_logger

skip_windows = mark.skipif(sys.platform == 'win32',
                           reason='Not supported on windows')
skip_windows_port_reuse = mark.skipif(sys.platform == 'win32',
                                      reason='Windows allows port reuse')
skip_windows_any_port = mark.skipif(sys.platform == 'win32',
                                    reason='Windows allows binding to well '
                                    'known ports')
skip_windows_spawn = mark.skipif(sys.platform == 'win32',
                                 reason='Windows does not support fork')
skip_windows_ipc = mark.skipif(sys.platform == 'win32',
                               reason='Windows does not support IPC')


def append_received(agent, message, topic=None):
    agent.received.append(message)


def set_received(agent, message, topic=None):
    agent.received = message

Exemplo n.º 4
0
    import gevent
    from zmq import green as gzmq
    have_gevent = True
except ImportError:
    have_gevent = False


PYPY = 'PyPy' in sys.version

#-----------------------------------------------------------------------------
# skip decorators (directly from unittest)
#-----------------------------------------------------------------------------

_id = lambda x: x

skip_pypy = mark.skipif(PYPY, reason="Doesn't work on PyPy")
require_zmq_4 = mark.skipif(zmq.zmq_version_info() < (4,), reason="requires zmq >= 4")

#-----------------------------------------------------------------------------
# Base test class
#-----------------------------------------------------------------------------

class BaseZMQTestCase(TestCase):
    green = False
    
    @property
    def Context(self):
        if self.green:
            return gzmq.Context
        else:
            return zmq.Context
Exemplo n.º 5
0
__author__ = 'Gennady Kovalev <*****@*****.**>'
__copyright__ = '(c) 2016-2018 Business group for development management'
__licence__ = 'For license information see LICENSE'

from os import environ
from pytest import fixture, mark

from bigur.store import db


@fixture
def debug(caplog):
    '''Turn debug on.'''
    from logging import getLogger, DEBUG
    caplog.set_level(DEBUG)
    return getLogger(__name__).debug


@fixture
async def database():
    '''Database connection.'''
    db.configure(environ.get('BIGUR_TEST_DB'))
    yield db


mark.db_configured = mark.skipif(
    environ.get('BIGUR_TEST_DB') is None,
    reason='Please define BIGUR_TEST_DB with test database uri')
Exemplo n.º 6
0
try:
    import gevent
    from zmq import green as gzmq
    have_gevent = True
except ImportError:
    have_gevent = False

PYPY = 'PyPy' in sys.version

#-----------------------------------------------------------------------------
# skip decorators (directly from unittest)
#-----------------------------------------------------------------------------

_id = lambda x: x

skip_pypy = mark.skipif(PYPY, reason="Doesn't work on PyPy")
require_zmq_4 = mark.skipif(zmq.zmq_version_info() < (4, ),
                            reason="requires zmq >= 4")

#-----------------------------------------------------------------------------
# Base test class
#-----------------------------------------------------------------------------


class BaseZMQTestCase(TestCase):
    green = False

    @property
    def Context(self):
        if self.green:
            return gzmq.Context
Exemplo n.º 7
0
EVENT = join(EXAMPLES, 'palace-event.py')
HRTF = join(EXAMPLES, 'palace-hrtf.py')
INFO = join(EXAMPLES, 'palace-info.py')
LATENCY = join(EXAMPLES, 'palace-latency.py')
REVERB = join(EXAMPLES, 'palace-reverb.py')
STDEC = join(EXAMPLES, 'palace-stdec.py')
TONEGEN = join(EXAMPLES, 'palace-tonegen.py')

MADEUP_DEVICE = str(uuid4())
REVERB_PRESETS = choices(reverb_preset_names, k=5)
WAVEFORMS = [
    'sine', 'square', 'sawtooth', 'triangle', 'impulse', 'white-noise'
]

travis_macos = bool(environ.get('TRAVIS')) and system() == 'Darwin'
skipif_travis_macos = mark.skipif(travis_macos, reason='Travis CI for macOS')


def capture(*argv):
    """Return the captured standard output of given Python script."""
    return run([executable, *argv], stdout=PIPE).stdout.decode()


@skipif_travis_macos
def test_event(aiff, flac, mp3, ogg, wav):
    """Test the event handling example."""
    event = capture(EVENT, aiff, flac, mp3, ogg, wav)
    assert 'Opened' in event
    assert f'Playing {aiff}' in event
    assert f'Playing {flac}' in event
    assert f'Playing {mp3}' in event
Exemplo n.º 8
0
from gnome.environment import Wind, Water, Waves, Tide

from gnome.spill import point_line_release_spill

from gnome.movers import RandomMover, WindMover, CatsMover
from gnome.weatherers import Evaporation, ChemicalDispersion, Burn, Skimmer

from gnome.outputters import WeatheringOutput, TrajectoryGeoJsonOutput

from gnome.multi_model_broadcast import ModelBroadcaster
from conftest import testdata, test_oil

from pprint import PrettyPrinter
pp = PrettyPrinter(indent=2, width=120)

pytestmark = mark.skipif("sys.platform=='win32'", reason="skip on windows")


def make_model(uncertain=False,
               geojson_output=False):

    start_time = datetime(2012, 9, 15, 12, 0)
    mapfile = testdata["lis"]["map"]

    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
Exemplo n.º 9
0
#  You should have received a copy of the GNU General Public License along with
#  PyLaDa.  If not, see <http://www.gnu.org/licenses/>.
###############################

from pytest import fixture, mark


def has_mpi4py():
    try:
        import mpi4py
        return True
    except ImportError:
        return False


mpi4py_required = mark.skipif(not has_mpi4py(),
                              reason="mpi4py is not installed.")


@fixture
def executable():
    from os.path import join, dirname
    from pylada.process.tests.pifunctional import __file__ as executable
    return join(dirname(executable), "pifunctional.py")


@fixture
def comm():
    from pylada import default_comm
    result = default_comm.copy()
    result['n'] = 4
    return result
Exemplo n.º 10
0
#
# SPDX-License-Identifier: GPL-3.0+

from contextlib import contextmanager
from os import path
from shutil import which
from subprocess import CalledProcessError
from tarfile import open as open_tar
from tempfile import TemporaryDirectory

from pytest import mark, raises

from jnrbase.git import find_tag


pytestmark = mark.skipif(not which('git'), reason='Requires git')


@contextmanager
def tarball_data(tar_name):
    """Extract a tarball for test usage

    This fixture extracts a tarball, and returns the path to the extracted
    files.

    :see: `tar_name`
    """
    data_dir = path.join(path.dirname(__file__), 'data', 'git')
    with open_tar(path.join(data_dir, tar_name + '.tar'), 'r:') as tar:
        with TemporaryDirectory() as temp_dir:
            tar.extractall(temp_dir)
Exemplo n.º 11
0
# TODO: TEST NON_HERMITIAN

from pytest import fixture, mark
import numpy as np
import scipy.sparse as sp
from numpy.testing import assert_allclose
from ... import qu, rand_uni, ldmul, rand_matrix, scipy_svds, SLEPC4PY_FOUND, rand_herm, seigsys, overlap, eye

if SLEPC4PY_FOUND:
    from ...solve.slepc_solver import slepc_seigsys, slepc_svds, convert_to_petsc, new_petsc_vec


slepc4py_notfound_msg = "No SLEPc4py installation"
slepc4py_test = mark.skipif(not SLEPC4PY_FOUND, reason=slepc4py_notfound_msg)


@fixture
def prematsparse():
    u = rand_uni(4)
    a = u @ ldmul(np.array([-1, 2, 4, -3]), u.H)
    a = qu(a, sparse=True)
    return u, a


@fixture
def bigsparsemat():
    return rand_matrix(100, sparse=True, density=0.1)


# --------------------------------------------------------------------------- #
# TESTS                                                                       #
Exemplo n.º 12
0
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

import json
import logging
import os.path as op

from pytest import mark

from ..utils import (Bunch, Path, open_text, save_text,
                     pandoc, has_pandoc, get_pandoc_formats)

logger = logging.getLogger(__name__)

require_pandoc = mark.skipif(not(has_pandoc()),
                             reason='pypandoc is not available')


#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------

def test_bunch():
    obj = Bunch()
    obj['a'] = 1
    assert obj.a == 1
    obj.b = 2
    assert obj['b'] == 2
    assert obj.copy().a == 1

Exemplo n.º 13
0
                x: 3
                z: 1
            """
        )
    )
    assert cfg == {"a": {"x": 1}, "b": {"y": 2}, "c": {"x": 3, "y": 2, "z": 1}}


@mark.parametrize(
    "path_type",
    [
        param("Path", id="path"),
        param(
            "PosixPath",
            marks=mark.skipif(
                platform.system() == "Windows", reason="requires posix path support"
            ),
            id="posixpath",
        ),
        param(
            "WindowsPath",
            marks=mark.skipif(
                platform.system() != "Windows", reason="requires windows"
            ),
            id="windowspath",
        ),
    ],
)
def test_create_path(path_type: str) -> None:
    yaml_document = dedent(
        """\
Exemplo n.º 14
0
from pytest import mark

from libearth.compat import IRON_PYTHON
if IRON_PYTHON:
    import System  # noqa: to import bytes.ToByteArray()
    from libearth.compat.clrxmlreader import IteratorStream, TreeBuilder

iron_python_only = mark.skipif('not IRON_PYTHON',
                               reason='Test only for Iron Python')


@iron_python_only
def test_iterator_stream():
    is_ = IteratorStream([b'abc', b'def', b'ghi', b'jkl', b'mno'])
    assert is_.Position == 0
    assert is_.Length == 15, 'is_.Length = ' + repr(is_.Length)
    read_byte = is_.ReadByte()
    assert read_byte == ord(b'a')
    assert is_.Position == 1
    assert len(is_.buffer) == 1, 'is_.buffer = ' + repr(is_.buffer)
    buffer_ = b'buffer'.ToByteArray()
    read_size = is_.Read(buffer_, 0, 6)
    assert read_size == 6 and bytes(buffer_) == b'bcdefg'
    assert is_.Position == 7
    assert len(is_.buffer) == 1, 'is_.buffer = ' + repr(is_.buffer)
    read_size = is_.Read(buffer_, 1, 5)
    assert read_size == 5 and bytes(buffer_) == b'bhijkl'
    assert is_.Position == 12
    assert len(is_.buffer) == 0, 'is_.buffer = ' + repr(is_.buffer)
    read_size = is_.Read(buffer_, 0, 6)
    assert read_size == 3 and bytes(buffer_) == b'mnojkl'
Exemplo n.º 15
0
# -*- coding: utf-8 -*-
from pytest import mark, config

from dv.crawl import crawl, html_select
from dv.bugs import BugsRecentAlbum

crawlskip = mark.skipif(not config.getvalue('crawl'),
                        reason="crawl is not available")

def test_crawl():
    r = crawl('http://example.com')
    assert r is not None
    assert '<title>Example Domain</title>' in r


def test_html_select():
    doc = crawl('http://example.com')
    assert doc
    assert '<title>Example Domain</title>' in doc
    r = html_select(doc, xpath='//title')
    assert r is not None


@crawlskip
def test_crawl_bugs():
    bugs = BugsRecentAlbum()
    assert bugs.newest


def test_asset_bugs(f_page):
    bugs = BugsRecentAlbum()
Exemplo n.º 16
0
        ),
        # test in valid idle_delay
        (
            ["--idle-threshold", "1", "--idle-delay", "-1"],
            "error: --idle-delay value must be positive",
        ),
        # test invalid min-crashes value
        (["--min-crashes", "0"], "error: --min-crashes value must be positive"
         ),
        # test invalid repeat value
        (["--repeat", "-1"], "error: --repeat value must be positive"),
        # test running with rr without --logs set
        param(
            ["--rr"],
            "error: --logs must be set when using rr",
            marks=[mark.skipif(system() != "Linux", reason="Linux only")],
        ),
        # test missing signature file
        (["--sig", "missing"], "error: signature file not found"),
    ],
)
def test_replay_args_02(capsys, mocker, tmp_path, args, msg):
    """test ReplayArgs.parse_args() - sanity checks"""
    mocker.patch("grizzly.args.Path.read_text",
                 autospec=True,
                 return_value="0")
    target = "target1"
    mocker.patch("grizzly.args.scan_plugins",
                 autospec=True,
                 return_value=[target])
    fake_bin = tmp_path / "fake.bin"
Exemplo n.º 17
0
    _get_file,
    _merge_str,
    _shorten_string,
    _get_resources_path,
    _save_resources,
    _load_resources,
    get_test_file_path,
    _create_dir_if_not_exists,
    pandoc,
    has_pandoc,
    get_pandoc_formats,
)

logger = logging.getLogger(__name__)

require_pandoc = mark.skipif(not (has_pandoc()),
                             reason='pypandoc is not available')

#-------------------------------------------------------------------------------------------------
# Tests
#-------------------------------------------------------------------------------------------------


def test_bunch():
    obj = Bunch()
    obj['a'] = 1
    assert obj.a == 1
    obj.b = 2
    assert obj['b'] == 2
    assert obj.copy().a == 1

Exemplo n.º 18
0
from pytest import mark, raises

import os
import shutil
import sys

from pathstring import Path

if sys.platform != "win32":
    import grp
    import pwd

pytestmark = mark.skipif(sys.platform == "win32",
                         reason="tests for posix only")


def test_multiple_absolute_paths_should_anchor_to_last():
    assert Path("/etc", "/usr", "lib64") == "/usr/lib64"


def test_drive_should_be_empty():
    assert Path("/etc").drive == ""


def test_as_posix_should_return_same_result():
    assert Path("/etc/passwd").as_posix() == "/etc/passwd"


def test_as_uri_should_return_file_uri():
    assert Path("/etc/passwd").as_uri() == "file:///etc/passwd"
Exemplo n.º 19
0
def validate_url_404(url):
    res = call('curl -sI "%s" | grep -iq "404 Not found"' % url, shell=True)
    return bool(res)


def mk_gitlink(url, codir, browser, linkurl, headrev):
    codir = '%s/%s' % (test_repo_dir, codir)
    repo = Repo(url, codir, headrev)
    repo.clone()
    repo.config('link.browser', browser)
    repo.config('link.url', linkurl)

    def gitlink_lib(args):
        os.chdir(codir)
        out = StringIO()
        main(args.split(' '), out)
        return out.getvalue().rstrip()

    def gitlink_exe(args):
        os.chdir(codir)
        cmd = ['%s/../git-link' % here]
        cmd.extend(args.split())
        return check_output(cmd).rstrip().decode('utf8')

    return gitlink_lib, gitlink_exe


skipif_no_gitlink = mark.skipif(not isfile(pjoin(here, '../git-link')),
                                reason='missing git-link.zip')
Exemplo n.º 20
0
from tools.simulation.SimulationTool import SimulationTool
from tools.translation.verilator_sim import TranslationTool
from tools.translation.cpp_sim       import get_cpp
from tools.integration.verilog       import VerilogModel

#-----------------------------------------------------------------------
# py.test decorators
#-----------------------------------------------------------------------

from pytest          import mark            as _mark
from distutils.spawn import find_executable as _find_executable
from os.path         import exists          as _exists

_has = lambda x: _find_executable( x ) != None

requires_xcc = _mark.skipif( not( _has('maven-gcc') and _has('maven-objdump') ),
                             reason='requires cross-compiler toolchain' )

requires_vmh = _mark.skipif( not _exists('../tests/build/vmh'),
                             reason='requires vmh files' )

requires_iverilog  = _mark.skipif( not( _has('iverilog') ),
                                   reason='requires iverilog' )

requires_verilator = _mark.skipif( not( _has('verilator') ),
                                   reason='requires verilator' )

#-----------------------------------------------------------------------
# pymtl namespace
#-----------------------------------------------------------------------

__all__ = [ # Model Construction
Exemplo n.º 21
0
    param(
        "2^10^ greater than 2^9^.",
        "<p>2<sup>10</sup> greater than 2<sup>9</sup>.</p>",
        id="Multiple substitutions",
    ),
]


@fixture(
    scope="session",
    params=[
        param([SuperscriptExtension()], id="Direct Extension"),
        param(
            ["mdx_superscript"],
            marks=mark.skipif(
                md_version < (2, 6),
                reason="Module matching by full name added in Markdown 2.6",
            ),
            id="Full module name",
        ),
        param(["superscript"], id="Short module name"),
    ],
)
def extensions(request):
    """Parameterized Fixture for extensions kwarg of markdown"""
    return request.param


@mark.parametrize(TEXT_DATA_FIELDS, TEXT_DATA)
def test_superscript_extension(markdown_text, expected_html, extensions):
    """Test the superscript extensions
Exemplo n.º 22
0
from falkon.tests.gen_random import gen_random, gen_sparse_matrix
from falkon.utils import decide_cuda

n32 = np.float32
n64 = np.float64
# Global dimensions
n = 1000
m = 850
d = 10
t = 5
max_mem_dense = 0.5 * 2**20
max_mem_sparse = 0.5 * 2**20
cpu_params = [
    pytest.param(True),
    pytest.param(
        False, marks=[mark.skipif(not decide_cuda(), reason="No GPU found.")])
]


def choose_on_dtype(dtype):
    if dtype == np.float64 or dtype == torch.float64:
        return 1e-12
    else:
        return 1e-4


def numpy_to_torch_type(dt):
    if dt == np.float32:
        return torch.float32
    elif dt == np.float64:
        return torch.float64
Exemplo n.º 23
0
import os
from pytest import fixture, mark
import numpy as np
import xarray as xr
from ..plot.matplotlib_plotter import xmlineplot
from ..plot.plotly_plotter import ilineplot


DISPLAY_PRESENT = 'DISPLAY' in os.environ
no_display_msg = "No display found."
needs_display = mark.skipif(not DISPLAY_PRESENT, reason=no_display_msg)


@fixture
def dataset_3d():
    x = [1, 2, 3, 4, 5, 6, 8]
    z = ['a', 'b', 'c', 'd']
    d = np.random.rand(7, 4)
    ds = xr.Dataset()
    ds["x"] = x
    ds["z"] = z
    ds["y"] = (("x", "z"), d)
    return ds


# --------------------------------------------------------------------------- #
# TESTS                                                                       #
# --------------------------------------------------------------------------- #

class TestXmlineplot:
    @needs_display
Exemplo n.º 24
0
from quimb import (qu, rand_uni, ldmul, rand_matrix, rand_herm, rand_pos,
                   rand_ket, eigh, eye, norm)
from quimb.linalg import SLEPC4PY_FOUND
from quimb.linalg.scipy_linalg import svds_scipy
if SLEPC4PY_FOUND:
    from quimb.linalg.slepc_linalg import (
        eigs_slepc,
        svds_slepc,
        convert_mat_to_petsc,
        new_petsc_vec,
        mfn_multiply_slepc,
        ssolve_slepc,
    )

slepc4py_notfound_msg = "No SLEPc4py installation"
slepc4py_test = mark.skipif(not SLEPC4PY_FOUND, reason=slepc4py_notfound_msg)


@fixture
def prematsparse():
    u = rand_uni(4)
    a = u @ ldmul(np.array([-1, 2, 4, -3]), u.H)
    a = qu(a, sparse=True)
    return u, a


@fixture
def bigsparsemat():
    return rand_matrix(100, sparse=True, density=0.1)

Exemplo n.º 25
0
import zlib
import numpy as np
from lenskit.util import random

from pytest import mark

new_gen = mark.skipif(not random._have_gen,
                      reason="requires NumPy with generators")
old_gen = mark.skipif(random._have_gen, reason="only for legacy NumPy")


@new_gen
def test_generator():
    rng = random.rng()
    assert isinstance(rng, np.random.Generator)


@new_gen
def test_generator_seed():
    rng = random.rng(42)
    assert isinstance(rng, np.random.Generator)


@new_gen
def test_generator_seed_seq():
    seq = np.random.SeedSequence(42)
    rng = random.rng(seq)
    assert isinstance(rng, np.random.Generator)


def test_generator_legacy():
Exemplo n.º 26
0
     "dict_enum",
     int,
     Color,
     False,
     Dict[Color, int],
     id="dict_enum",
 ),
 param(SubscriptedList, "list", int, Any, False, List[int], id="list_int"),
 param(
     SubscriptedDictOpt,
     "opt_dict",
     int,
     str,
     True,
     Optional[Dict[str, int]],
     marks=mark.skipif(sys.version_info < (3, 7), reason="requires Python 3.7"),
     id="opt_dict",
 ),
 param(
     SubscriptedDictOpt,
     "dict_opt",
     Optional[int],
     str,
     False,
     Dict[str, Optional[int]],
     marks=mark.skipif(sys.version_info < (3, 7), reason="requires Python 3.7"),
     id="dict_opt",
 ),
 param(
     SubscriptedListOpt,
     "opt_list",
Exemplo n.º 27
0
        orb.propagator = Kepler(
            timedelta(seconds=60),
            get_body('Earth')
        )
        return orb


@fixture
def jplfiles():
    config['env'] = {
        'jpl': [
            str(Path(__file__).parent / "data" / "jpl" / "de403_2000-2020.bsp"),
            str(Path(__file__).parent / "data" / "jpl" / "pck00010.tpc"),
            str(Path(__file__).parent / "data" / "jpl" / "gm_de431.tpc"),
        ]
    }


# Specific for dynamically skipping the test if matplotlib is not present
# as it is not a dependency of the library, but merely a convenience
def _skip_if_no_mpl():
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        return True
    else:
        return False


skip_if_no_mpl = mark.skipif(_skip_if_no_mpl(), reason="Missing matplotlib dependency")
Exemplo n.º 28
0
from gnome.spill import point_line_release_spill

from gnome.movers import RandomMover, WindMover, CatsMover
from gnome.weatherers import Evaporation, ChemicalDispersion, Burn, Skimmer

from gnome.outputters import WeatheringOutput, TrajectoryGeoJsonOutput

from gnome.multi_model_broadcast import ModelBroadcaster
from conftest import testdata, test_oil

from pprint import PrettyPrinter

pp = PrettyPrinter(indent=2, width=120)

pytestmark = mark.skipif("sys.platform=='win32'", reason="skip on windows")


def make_model(uncertain=False, geojson_output=False):
    print 'initializing the model'

    start_time = datetime(2012, 9, 15, 12, 0)
    mapfile = testdata["lis"]["map"]

    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
Exemplo n.º 29
0
    try:
        git = run(['which', 'git']).strip()
    except Exception:
        return False
    return git != ""


def is_bzr_configured():
    try:
        bzr = run(['which', 'bzr']).strip()
    except Exception:
        return False
    return bzr != ""


requires_bzr = mark.skipif(not is_bzr_configured(),
                           reason='bzr not installed/configured')

requires_git = mark.skipif(not is_git_configured(),
                           reason='git not installed/configured')


@requires_git
def test_git(monkeypatch):
    dir = tempfile.mkdtemp()
    monkeypatch.chdir(dir)
    run(['git', 'init', '.'])
    run(['git', 'config', 'user.email', '*****@*****.**'])
    run(['git', 'config', 'user.name', 'someone'])
    run(['touch', 'foo'])
    run(['git', 'add', 'foo'])
    run(['git', 'commit', '-m', 'init'])
Exemplo n.º 30
0
 def skipif(cond):
     assert cond in (True, False)
     return mark.skipif(repr(cond))
Exemplo n.º 31
0
#  You should have received a copy of the GNU General Public License along with
#  PyLaDa.  If not, see <http://www.gnu.org/licenses/>.
###############################

from pytest import fixture, mark


def has_mpi4py():
    try:
        import mpi4py
        return True
    except ImportError:
        return False


mpi4py_required = mark.skipif(
    not has_mpi4py(), reason="mpi4py is not installed.")


@fixture
def executable():
    from os.path import join, dirname
    from pylada.process.tests.pifunctional import __file__ as executable
    return join(dirname(executable), "pifunctional.py")


@fixture
def comm():
    from pylada import default_comm
    result = default_comm.copy()
    result['n'] = 4
    return result
Exemplo n.º 32
0
from pathlib import Path

import pymodaq.daq_utils.gui_utils.dock
from pymodaq.daq_utils.config import Config, get_set_preset_path
from pytest import fixture, mark
from pymodaq.daq_utils import daq_utils as utils
from pymodaq.daq_utils.conftests import qtbotskip, main_modules_skip

pytestmark = mark.skipif(qtbotskip, reason='qtbot issues but tested locally')

preset_path = get_set_preset_path()
config = Config()


@fixture
def init_qt(qtbot):
    return qtbot


@fixture
def main(qtbot):
    from qtpy import QtWidgets
    from pymodaq.dashboard import DashBoard
    from pymodaq.daq_scan import DAQ_Scan
    from pymodaq.daq_utils import gui_utils as gutils

    win = QtWidgets.QMainWindow()
    area = pymodaq.daq_utils.gui_utils.dock.DockArea()
    win.setCentralWidget(area)
    win.resize(1000, 500)
    win.setWindowTitle('PyMoDAQ Dashboard')
Exemplo n.º 33
0
    try:
        sp_out = sp.check_output([dcmqrscp_path,
                                  "--version"]).decode("latin-1")
    except (FileNotFoundError, sp.CalledProcessError):
        return None
    first = sp_out.split("\n")[0]
    return tuple(int(x) for x in re.match(DCMTK_VER_RE, first).groups())


DCMTK_VERSION = get_dcmtk_version()

dcmtk_base_port = 62760

dcmtk_base_name = "DCMTKAE"

has_dcmtk = mark.skipif(DCMTK_VERSION is None,
                        reason="can't find DCMTK command 'dcmqrscp'")

dcmtk_priv_sop_retr_xfail = mark.xfail(
    DCMTK_VERSION is None or DCMTK_VERSION < DCMTK_PRIV_RETR_VERS,
    reason="dcmqrscp version doesn't support retrieving private "
    "SOPClasses",
)

dcmtk_priv_sop_send_xfail = mark.xfail(
    DCMTK_VERSION is None or DCMTK_VERSION < DCMTK_PRIV_SEND_VERS,
    reason="dcmqrscp version doesn't support sending private "
    "SOPClasses",
)

dcmtk_config_tmpl = """\
NetworkTCPPort  = {dcmtk_node.port}
Exemplo n.º 34
0
    @mark.xfail
    def test_mode(self):
        raise NotImplementedError

    def test_sep(self, tmpdir, frame):
        store = CSVStore(str(tmpdir), sep='_')
        key = '/data'
        store[key] = frame
        # separator is not os.sep, so no subdirectories are created.
        assert not any(
            os.path.isdir(os.path.join(str(tmpdir), subdir))
            for subdir in os.listdir(str(tmpdir)))


@mark_class(mark.skipif(tables is None, reason='HDFStore requires pytables'))
class TestHDFStore(StoreTests):
    @yield_fixture
    def store(self):
        if os.name == 'nt':
            # pytables does not like mkstemp in windows
            fullpath = tempfile.mktemp(suffix='.h5')
        else:
            ntf = tempfile.NamedTemporaryFile(suffix='.h5')
            fullpath = ntf.name
        directory, filename = os.path.split(fullpath)
        basename, ext = os.path.splitext(filename)
        store = HDFStore(directory, basename, ext=ext)
        try:
            yield store
        finally:
Exemplo n.º 35
0
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals

import sys

from pytest import importorskip, mark, raises

pytestmark = mark.skipif(
    not sys.platform.startswith('linux'),
    reason="cpo is only available on Linux"
)

from translate.misc import wStringIO
from translate.misc.multistring import multistring
from translate.storage import test_po


cpo = importorskip("translate.storage.cpo")


class TestCPOUnit(test_po.TestPOUnit):
    UnitClass = cpo.pounit

    def test_plurals(self):
        """Tests that plurals are handled correctly."""
        unit = self.UnitClass("Cow")
        unit.msgid_plural = ["Cows"]
        assert isinstance(unit.source, multistring)
        assert unit.source.strings == ["Cow", "Cows"]
        assert unit.source == "Cow"
Exemplo n.º 36
0
import pandas as pd
import numpy as np

from pytest import approx, mark

import lenskit.util.test as lktu

_log = logging.getLogger(__name__)

simple_df = pd.DataFrame({
    'item': [1, 1, 2, 3],
    'user': [10, 12, 10, 13],
    'rating': [4.0, 3.0, 5.0, 2.0]
})

need_skl = mark.skipif(not svd.SKL_AVAILABLE,
                       reason='scikit-learn not installed')


@need_skl
def test_svd_basic_build():
    algo = svd.BiasedSVD(2)
    algo.fit(simple_df)

    assert algo.user_components_.shape == (3, 2)


@need_skl
def test_svd_predict_basic():
    algo = svd.BiasedSVD(2)
    algo.fit(simple_df)
Exemplo n.º 37
0
    def chdir(self):
        os.chdir(self.local)

def validate_url_404(url):
    res = call('curl -sI "%s" | grep -iq "404 Not found"' % url, shell=True)
    return bool(res)

def mk_gitlink(url, codir, browser, linkurl, headrev):
    codir = '%s/%s' % (test_repo_dir, codir)
    repo = Repo(url, codir, headrev)
    repo.clone()
    repo.config('link.browser', browser)
    repo.config('link.url', linkurl)

    def gitlink_lib(args):
        os.chdir(codir)
        out = StringIO()
        main(args.split(' '), out)
        return out.getvalue().rstrip()

    def gitlink_exe(args):
        os.chdir(codir)
        cmd = ['%s/../git-link' % here]
        cmd.extend(args.split())
        return check_output(cmd).rstrip().decode('utf8')

    return gitlink_lib, gitlink_exe

skipif_no_gitlink = mark.skipif(not isfile(pjoin(here, '../git-link')), reason='missing git-link.zip')
Exemplo n.º 38
0
import os
from pytest import fixture, mark
import numpy as np
import xarray as xr
from ..plot.matplotlib_plotter import xmlineplot
from ..plot.plotly_plotter import ilineplot

DISPLAY_PRESENT = 'DISPLAY' in os.environ
no_display_msg = "No display found."
needs_display = mark.skipif(not DISPLAY_PRESENT, reason=no_display_msg)


@fixture
def dataset_3d():
    x = [1, 2, 3, 4, 5, 6, 8]
    z = ['a', 'b', 'c', 'd']
    d = np.random.rand(7, 4)
    ds = xr.Dataset()
    ds["x"] = x
    ds["z"] = z
    ds["y"] = (("x", "z"), d)
    return ds


# --------------------------------------------------------------------------- #
# TESTS                                                                       #
# --------------------------------------------------------------------------- #


class TestXmlineplot:
    @needs_display
Exemplo n.º 39
0
from pytest import mark, raises

import os
import shutil
import sys

from pathstring import Path


pytestmark = mark.skipif(sys.platform != "win32", reason="tests for windows only")


def test_multiple_absolute_paths_should_anchor_to_last():
    assert Path("c:\\Windows", "d:bar") == "d:bar"


def test_changing_local_root_should_not_discard_drive():
    assert Path("c:\\Windows", "\\Program Files") == "c:\\Program Files"


def test_drive_should_be_a_part_of_first_component():
    assert Path("c:\\Program Files\\PSF").parts == ("c:\\", "Program Files", "PSF")


def test_drive_should_be_drive_letter_with_colon():
    assert Path("c:\\Program Files\\").drive == "c:"


def test_empty_drive_should_be_empty_string():
    assert Path("\\Program Files\\PSF").drive == ""
Exemplo n.º 40
0
import fcntl
import termios

from mock import Mock, patch
from pytest import skip, mark

from invoke.terminals import pty_size, bytes_to_read, WINDOWS

# Skip on Windows CI, it may blow up on one of these tests
pytestmark = mark.skipif(
    WINDOWS, reason="Low level terminal tests only work well on POSIX")

# NOTE: 'with character_buffered()' tests are in runners.py as it's a lot
# easier to test some aspects in a non-unit sense (e.g. a keyboard-interrupting
# Runner subclass). MEH.


class terminals:
    class pty_size:
        @patch("fcntl.ioctl", wraps=fcntl.ioctl)
        def calls_fcntl_with_TIOCGWINSZ(self, ioctl):
            # Test the default (Unix) implementation because that's all we
            # can realistically do here.
            pty_size()
            assert ioctl.call_args_list[0][0][1] == termios.TIOCGWINSZ

        @patch("sys.stdout")
        @patch("fcntl.ioctl")
        def defaults_to_80x24_when_stdout_not_a_tty(self, ioctl, stdout):
            # Make sure stdout acts like a real stream (means failure is
            # more obvious)
Exemplo n.º 41
0
from __future__ import absolute_import

import sys
import subprocess
import platform
import time

from pytest import fixture, mark, param
from distutils.spawn import find_executable
from click.testing import CliRunner

from pystack import cli_main, tolerate_missing_locale


skipif_non_gdb = mark.skipif(
    not find_executable('gdb'), reason='gdb not found')
skipif_non_lldb = mark.skipif(
    not find_executable('lldb'), reason='lldb not found')
skipif_darwin = mark.skipif(
    platform.system().lower() == 'darwin', reason='gdb on darwin is unstable')


STATEMENTS = {
    'sleep': '__import__("time").sleep(360)',
}


@fixture
def process(request):
    args = [sys.executable, '-c', request.param]
    process = subprocess.Popen(args)
Exemplo n.º 42
0
import os
from time import sleep

from pytest import mark

pytestmark = mark.skipif(os.getenv('TEST_LIVE') != "True",
                         reason="tests against a real, live Drip account")


def test_create_or_update_subscribers(live_client):
    check = live_client.session.get(
        'https://api.getdrip.com/v2/5706364/subscribers/[email protected]'
    ).json()['subscribers'][0]
    assert 'custom_fields' in check
    assert 'test_custom_field' in check['custom_fields']
    assert check['custom_fields']['test_custom_field'] == 'init'

    response = live_client.create_or_update_subscribers([{
        'email': '*****@*****.**',
        'custom_fields': {
            'test_custom_field': '1'
        }
    }])
    assert type(response) == bool
    assert response

    sleep(2)  # (!)
    confirm = live_client.session.get(
        'https://api.getdrip.com/v2/5706364/subscribers/[email protected]'
    ).json()['subscribers'][0]
    assert 'custom_fields' in confirm
Exemplo n.º 43
0
import fcntl
import termios

from mock import Mock, patch
from pytest import skip, mark

from dued.terminales import pty_dimension, bytes_a_leer, WINDOWS

# Skip on Windows CI, it may blow up on one of these pruebas
marcapytest = mark.skipif(
    WINDOWS,
    motivo="Las pruebas de terminal a bajo nivel solo funcionan bien en POSIX")

# NOTE: las pruebas 'con caracter_buffereado()' están en corredores.py ya que
# es mucho más fácil probar algunos aspectos en un sentido no unitario
# (por ejemplo, una subclase Corredor que interrumpe el teclado). Bah.


class terminales:
    class pty_dimension:
        @patch("fcntl.ioctl", wraps=fcntl.ioctl)
        def fcntl_llamabas_con_TIOCGWINSZ(self, ioctl):
            # Pruebe la implementación predeterminada (Unix) porque eso es
            # todo lo que podemos hacer de manera realista aquí.
            pty_dimension()
            assert ioctl.llamada_a_lista_de_args[0][0][1] == termios.TIOCGWINSZ

        @patch("sys.stdout")
        @patch("fcntl.ioctl")
        def pordefecto_a_80x24_cuando_stdout_no_es_tty(self, ioctl, stdout):
            # Asegúrese de que stdout actúe como una transmisión real
Exemplo n.º 44
0
import sys

from pytest import mark

skip_windows = mark.skipif(sys.platform == 'win32',
                           reason='Not supported on windows')
skip_windows_port_reuse = mark.skipif(sys.platform == 'win32',
                                      reason='Windows allows port reuse')
skip_windows_any_port = mark.skipif(
    sys.platform == 'win32',
    reason='Windows allows binding to well-known ports',
)
skip_windows_spawn = mark.skipif(sys.platform == 'win32',
                                 reason='Windows does not support fork')
skip_windows_ipc = mark.skipif(sys.platform == 'win32',
                               reason='Windows does not support IPC')


def append_received(agent, message, topic=None):
    agent.received.append(message)


def set_received(agent, message, topic=None):
    agent.received = message


def echo_handler(agent, message):
    return message
from pytest import mark

from libearth.compat import IRON_PYTHON
if IRON_PYTHON:
    import System  # noqa: to import bytes.ToByteArray()
    from libearth.compat.clrxmlreader import IteratorStream, TreeBuilder


iron_python_only = mark.skipif('not IRON_PYTHON',
                               reason='Test only for Iron Python')


@iron_python_only
def test_iterator_stream():
    is_ = IteratorStream([b'abc', b'def', b'ghi', b'jkl', b'mno'])
    assert is_.Position == 0
    assert is_.Length == 15, 'is_.Length = ' + repr(is_.Length)
    read_byte = is_.ReadByte()
    assert read_byte == ord(b'a')
    assert is_.Position == 1
    assert len(is_.buffer) == 1, 'is_.buffer = ' + repr(is_.buffer)
    buffer_ = b'buffer'.ToByteArray()
    read_size = is_.Read(buffer_, 0, 6)
    assert read_size == 6 and bytes(buffer_) == b'bcdefg'
    assert is_.Position == 7
    assert len(is_.buffer) == 1, 'is_.buffer = ' + repr(is_.buffer)
    read_size = is_.Read(buffer_, 1, 5)
    assert read_size == 5 and bytes(buffer_) == b'bhijkl'
    assert is_.Position == 12
    assert len(is_.buffer) == 0, 'is_.buffer = ' + repr(is_.buffer)
    read_size = is_.Read(buffer_, 0, 6)
Exemplo n.º 46
0
# -*- coding: utf-8 -*-

import sys

from pytest import importorskip, mark, raises

pytestmark = mark.skipif(not sys.platform.startswith('linux'),
                         reason="cpo is only available on Linux")

from translate.misc import wStringIO
from translate.misc.multistring import multistring
from translate.storage import test_po

cpo = importorskip("translate.storage.cpo")


class TestCPOUnit(test_po.TestPOUnit):
    UnitClass = cpo.pounit

    def test_plurals(self):
        """Tests that plurals are handled correctly."""
        unit = self.UnitClass("Cow")
        unit.msgid_plural = ["Cows"]
        assert isinstance(unit.source, multistring)
        assert unit.source.strings == ["Cow", "Cows"]
        assert unit.source == "Cow"

        unit.target = ["Koei", "Koeie"]
        assert isinstance(unit.target, multistring)
        assert unit.target.strings == ["Koei", "Koeie"]
        assert unit.target == "Koei"
Exemplo n.º 47
0
# -*- coding:utf8 -*-
# It is a test root.
import os
from pytest import mark


current_dir = os.path.abspath(os.getcwd())
"""directory to run test"""

test_dir = os.path.abspath(os.path.dirname(__file__))
"""directory of it"""

skip_in_ci = mark.skipif("'FULL_TEST' not in os.environ")
"""Decorator to skip test in CI service(CircleCI)

If your test has dependencies for PySlide, decorate it.
CircleCI has time limit of 10 minutes, so failed to install PySide.
"""