Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest hangs when running with other threads

I am trying to run pytest from within python after running a thread, here is a simple example of the case:

import time
import threading
import pytest


class A(object):
    def __init__(self):
        self._thread_a = threading.Thread(target=self.do_a)
        self._thread_a.start()
        pytest.main()

    def do_a(self):
        print "a"
        time.sleep(2)
        self.do_a()


if __name__ == "__main__":
    a = A()

but pytest keeps hanging. this is what the output looks like:

============================= test session starts ==============================
platform darwin -- Python 2.7.10, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
metadata: {'Python': '2.7.10', 'Platform': 'Darwin-17.3.0-x86_64-i386-64bit', 'Packages': {'py': '1.5.2', 'pytest': '3.3.2', 'pluggy': '0.6.0'}, 'Plugins': {'session2file': '0.1.9', 'celery': '4.0.0','html': '1.16.1', 'metadata': '1.5.1'}}
rootdir: /Users/path/to/root/dir, inifile:
plugins: session2file-0.1.9, metadata-1.5.1, html-1.16.1, celery-4.0.0

and it just hangs like this until I force quit it. is there any way to make this work?

like image 870
BoooYaKa Avatar asked Feb 13 '18 14:02

BoooYaKa


1 Answers

Two things to mention:

  1. you possibly want to stop the thread if you code is done with something.
  2. you may also separate your code from the test code.

Lets say:

file.py

import time
import threading

class A(object):
    def __init__(self):
        self._thread_a = threading.Thread(target=self.do_a)
        self._thread_a.daemon = True
        self._thread_a.start()

    def do_a(self):
        print "a"
        time.sleep(2)
        self.do_a()

    def stop(self, timeout):
        self._thread_a.join(timeout)

test_file.py

import pytest

from .file import A

@pytest.fixture()
def a():
    return A()


def test_sth(a):
    a.start()
    print('I can do sth else')
    a.stop(timeout=1)
like image 168
ZhouQuan Avatar answered Oct 15 '22 00:10

ZhouQuan