Search code examples
google-app-enginepython-3.9ndb

Pytest & Google App Engine Testbed: Validation Error causes test to Fail Despite Being Expected?


I'm running into a weird error with pytest (version 7.4.2). I am writing some unit tests, including some that expect exceptions. In particular, I have this test that expects a validation error when you try to put() the record:

class TestMyModel:
    @pytest.mark.parametrize("value", [-7, -1, 0])
    def test_non_positive_value_validation_error(self, value):
        from models.datastore import MyModel
        from google.appengine.ext import ndb

        m = MyModel(
            _just_created=True,  
            value=value
            )
        
        with pytest.raises(Exception):
            m.put()

Now, as expected, m.put() is raising an exception. However, for some reason this error is causing the test to fail?!

FAILED src/models/datastore/test/test_my_model.py::TestMyModel::test_non_positive_value_validation_error[-7] - ValueError: IntegerProp(b'value', validator=<function MyModel.validate_value at 0x7fd44c257280>) must be a positive integer!

On the other hand, if I pass in a positive integer value, then the test fails because an exception was not thrown (as expected):

FAILED src/models/datastore/test/test_pick_bins.py::TestPickBins::test_non_positive_bin_num_validation_error[1] - Failed: DID NOT RAISE <class 'Exception'>

I've been searching around online, but no luck. At a loss for why this is happening. I also found that I get the same results if I use p = m.put_async() and never call p.get_result()...

For my unit tests, I have configured the testbed via an autouse fixture:

@pytest.fixture(scope='function', autouse=True)
def gae_testbed(request):
    from google.appengine.ext import testbed

    print('Activating gae_testbed...')

    tb = testbed.Testbed()
    tb.activate()
    tb.init_all_stubs()

    print ("gae_testbed initialized!")

    def teardown():
        print('Deactivating GAE stubs...')
        tb.deactivate()
        print('GAE stubs Deactived!')

    request.addfinalizer(teardown)
    return tb

Any help much appreciated!


Solution

  • The exception happens when you create the entity and not when you do the put.

    Wrapping the entity creation in pytest.raises() should fix it for you.