Git Product home page Git Product logo

pocha's People

Contributors

jharrilim avatar jj avatar rgs1 avatar rlgomes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

pocha's Issues

Cant run pocha on relative path starting with `test`

Pocha fails to import and run tests from a directory root of "test"

# Fails, no module named test
pocha test/test.py

Possible work around in discovery.py:search

for module in modules:
  module_path = os.path.dirname(module)
  sys_path = sys.path
  sys.path = ['.', module_path]
  try:
    ...
  finally:
    sys.path = sys_path

Migrating from pocha to pytest

I started using pocha 2 years ago shortly after it went out of active development. I just got around to migrating from it to pytest (with pytest-asyncio and pytest-mocha). In case someone else is in the same situation here is the script I wrote to migrate my test files. No citation needed for its use.

import os
import re
from collections import OrderedDict
from utilities import convert_to_camel_case
input_file = 'base.py'
input_file = os.path.join('test/', input_file)

with open(input_file) as f:
    input_data = f.read()


output = OrderedDict()
output['root'] = []
output['root'].append('import pytest')
skip_lines = 0
test_name = None
test_subsection = ['root']
has_before_each = {}
for line in input_data.split('\n'):
    # if a previous statement wants to skip lines then do it
    if skip_lines:
        skip_lines -= 1
        continue

    # ignore our custom decorator
    if 'make_sync_from_async' in line:
        continue

    # skip empty lines because they cause problems when deciding when to unindent
    line_sans_leading_spaces = re.sub(r'\s', '', line)
    if not line_sans_leading_spaces:
        output[test_subsection[-1]].append('')
        continue

    # ignore commented out code blocks
    if re.match(r'\s*#', line):
        output[test_subsection[-1]].append(line)
        continue

    # replace pocha with unitttest, but only once
    added_imports = False
    if 'from pocha import' in line:
        if not added_imports:
            output[test_subsection[-1]].append('from unittest import TestCase')
        continue

    # these values will be useful later
    extra_space, = re.match(r'(\s*)', line).groups()
    spacing = int(extra_space.count(' ')/4)
    describe_match = re.match(r".*@describe\('(.*)'\)", line)
    before_match = re.match('.*@before_each', line)
    after_match = re.match('.*@after_each', line)

    # replace describe statements
    if describe_match:
        class_name, = describe_match.groups()
        class_name = class_name.replace('tests', '').replace('test', '').strip().replace(' ', '_').capitalize()
        
        class_name = convert_to_camel_case(class_name)
        test_subsection.append(class_name)

        output[test_subsection[-1]] = []
        output[test_subsection[-1]].append('class Test' + class_name + '(TestCase):')

        mocha_name = ' :: '.join(test_subsection[1:])
        output[test_subsection[-1]].append("    '''" + mocha_name + "'''")
        skip_lines = 1

        continue

    # if the spacing decreases then we need to pop out of the subsection
    should_unindent = spacing < (len(test_subsection)-1)
    if should_unindent:
        test_subsection = test_subsection[:-1]

    # unittest doesn't use nesting like pocha does, so we need to remove spaces from the previous code
    indent = len(test_subsection)-2
    if indent > 0:
        extra_space = ' '*indent*4
        line = re.sub('^'+extra_space, '', line)

    
    # replace before_each statements
    if before_match or (after_match and test_subsection[-1] not in has_before_each):
        has_before_each[test_subsection[-1]] = True
        output[test_subsection[-1]].append('    @pytest.fixture(autouse=True)')
        output[test_subsection[-1]].append('    @pytest.mark.asyncio')
        output[test_subsection[-1]].append('    async def setup(self):')
        skip_lines = 2
    
    if before_match:
        continue

    # replace after_each statements
    if after_match:
        output[test_subsection[-1]].append('        try:')
        output[test_subsection[-1]].append('            yield')
        output[test_subsection[-1]].append('        except:')
        output[test_subsection[-1]].append('            pass')
        skip_lines = 1
        continue
    
    # replace it statements
    match = re.match(r".*@it\((.*)\)", line)
    if match:
        test_name, = match.groups()
        test_name = test_name.strip().strip("'").replace("\\'", '')
        # remove other arguments
        test_name = re.sub(r',.*skip=True.*', '', test_name)

        if 'skip=True' in line:
            output[test_subsection[-1]].append('    @pytest.mark.skip(reason="no way of testing this")')

        continue
    
    # modify the functions for it statements to support pytest-mocha
    if re.match('.*def _\(', line):
        if not test_name:
            continue

        if 'async def' in line:
            output[test_subsection[-1]].append('    @pytest.mark.asyncio')

        function_name = 'test_' + re.sub('[ -/,]', '_', test_name)
        
        line = re.sub(r'_\(.*', function_name + '(self):', line)
        # print(line)
        output[test_subsection[-1]].append(line)
        output[test_subsection[-1]].append("        '''{a}'''".format(a=test_name))
        test_name = None
        continue


    output[test_subsection[-1]].append(line)


output_path, output_file = os.path.split(input_file)
output_file = output_path + '/test_' + output_file
print('pytest -W ignore -k ' + input_file)
with open(output_file, 'w') as f:
    for k, v in output.items():
        f.write('\n'.join(v))
        f.write('\n\n')

get travis builds going

its easy enough and would give a nice badge for the state of master and any pending branches

beforeEach and afterEach don't apply to nested test cases

Mocha in Node.js would run this outer beforeEach function before all tests that occur within the top-level describe block, including those nested within inner describe blocks. Pocha does not apply the beforeEach to the test cases within inner describe blocks.

This code demonstrates this behavior. Note that "before each" is printed only once, showing that it was not run for "inner test":

from pocha import describe, beforeEach, it

@describe('tests')
def tests():
    @beforeEach
    def before():
        print('before each')

    @it('outer')
    def outer():
         print('outer')

    @describe('inner')
    def inner():

        @it('inner test')
        def inner_test():
            print('inner test')

outputs

  tests
before each
outer
    ✓ outer
    inner
inner test
        ✓ inner test

pip install fails with python 3.6

$ pip install pocha
Collecting pocha
  Downloading pocha-0.12.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-p117vgyi/pocha/setup.py", line 32, in <module>
        tests_require=load('requirements-dev.txt'),
      File "/tmp/pip-build-p117vgyi/pocha/setup.py", line 21, in load
        with open(filename, 'r') as input_file:
    FileNotFoundError: [Errno 2] No such file or directory: 'requirements-dev.txt'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-p117vgyi/pocha/

This is pip --version

pip 9.0.1 from /home/jmerelo/.pyenv/versions/3.6.1/lib/python3.6/site-packages (python 3.6)

This is python --version

Python 3.6.1

pocha to take a path to a python file as an argument.

pocha seems not to like when the python file with the tests is in a relative location to pocha:
using both pypi and building from source I get the following:

$: pocha ../tests/unit_test.py                                                      [ruby-2.4.2p198]
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/bin/pocha", line 11, in <module>
    load_entry_point('pocha==0.13.0', 'console_scripts', 'pocha')()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click/core.py", line 716, in __call__
    return self.main(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click/core.py", line 696, in main
    rv = self.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click/core.py", line 889, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/click/core.py", line 534, in invoke
    return callback(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pocha/cli.py", line 26, in cli
    tests = discover.search(path, expression)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pocha/discover.py", line 89, in search
    __import__(name)
ValueError: Empty module name

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.