Search code examples
pythonseleniumflaskpytestflask-testing

Getting a "Can't pickle local object 'LiveServerTestCase'" error when trying to use LiveServerTestCase to test Flask app


I am getting the error mentioned in the title once trying to run a unittest on my Flask app using LiveServerTestCase from flask_testing.

This is my test file:

from app import create_app
from flask_testing import LiveServerTestCase

class TestBase(LiveServerTestCase):

    def create_app(self):
        app = create_app()
        app.config.update(LIVESERVER_PORT=8847, TESTING=True)
        return app
    
    def test_app(self):
        self.assertEqual('test', 'test')

And this is the error I am getting once running my test using nose2:

AttributeError: Can't pickle local object 'LiveServerTestCase._spawn_live_server.<locals>.worker'

During handling of the above exception, another exception occurred:

AttributeError: 'NoneType' object has no attribute 'terminate'
Internal Error: runTests aborted: 'NoneType' object has no attribute 'terminate'

I really couldn't find anything helpful online about this issue,


Solution

  • I also ran into this issue and wanted to post so others might have somewhere to start and not need to sleuth as deep as me--

    I found a partial answer here that helped me figure out what was happening at least: https://github.com/pytest-dev/pytest-flask/issues/104

    apparently on OSX you need to run the following code to switch the multiprocessing style to fork instead of spawn which is the new default and incompatible with pickle:

    multiprocessing.set_start_method("fork")
    

    I'm developing on Windows, so from what I could tell I'm kinda out of luck- but I have another test server running CentOs so for proof of concept I tried running the tests there and it worked without issues!

    lastly: On another issue thread I found the following that might help and Windows people make a workaround: https://github.com/pytest-dev/pytest-flask/issues/54