mardi 20 septembre 2016

Mocking ConfigObj instances

Using ConfigObj, I want to test some section creation code:

def create_section(config, section):
    config.reload()
    if section not in config:
         config[session] = {}
         logging.info("Created new section %s.", section)
    else:
         logging.debug("Section %s already exists.", section)

I would like to write a few unit tests but I am hitting a problem. For example,

def test_create_section_created():
    config = Mock(spec=ConfigObj)  # ← This is not right…
    create_section(config, 'ook')
    assert 'ook' in config
    config.reload.assert_called_once_with()

Clearly, the test method will fail because of a TypeError as the argument of type 'Mock' is not iterable.

How can I define the config object as a mock?

How can I mock-setup asp.net core IConfiguration

I use moq to mock dependencies, and I used to setup service methods. but now I want to mock the IConfiguration injected to my service, and I dont sure how can I do that.

I tried instantiate it without moq. just like IConfiguration mockConfiguration = new foo() but everything I tried to insert in foo (configurationRoot\ dictionary, etc.) didn't work for me ("cannot resolve symbol configurationRoot"\ cannot implicitly convert dictionary to Iconfiguration).

I also tried with moq MockConfiguration = new Mock<IConfiguration>(); then MockConfiguration.Object["X:y:z"] = "t"; also not worked.

thanks!

django celery unit tests with pycharm 'No module named celery'

my tests work fine when my target is a single function (see 'Target' field in the image):

questionator.test_mturk_views.TestReport.submit

However, when I specify my target to include all tests within my questionator app:

questionator

I get this error:

Error ImportError: Failed to import test module: src.questionator.test_mturk_views Traceback (most recent call last):
File "C:\Python27\Lib\unittest\loader.py", line 254, in _find_tests module = self._get_module_from_name(name) File "C:\Python27\Lib\unittest\loader.py", line 232, in _get_module_from_name import(name) File "C:\Users\Andy\questionator_app\src__init__.py", line 5, in from .celery import app as celery_app # noqa ImportError: No module named celery

Note that my tests include my settings via 'Environment variables' (see this in the pic too):

DJANGO_SETTINGS_MODULE=questionator_app.settings.development;PYTHONUNBUFFERED=1

The celery documentation mentions a "Using a custom test runner to test with celery" but this is in the now defunct djcelery package. I did though copy/paste/tweak this mentioned test runner and used it as described, but I get the same error.

Unfortunately using CELERY_ALWAYS_EAGER also does not work http://ift.tt/2cDXjBz

I would appreciate some guidance. With best wishes, Andy.

enter image description here

Testing config module with mocha that depends on environment variable process.env.APP_ENV

I'm working on a project that uses the value in process.env.APP_ENV in order to select the appropiate config file for the current environment:

import prodParams from './production';
import stgParams from './staging';
import devParams from './development';

let params = devParams;
switch (process.env.APP_ENV) {
  case 'production':
    params = prodParams;
    break;
  case 'staging':
    params = stgParams;
    break;
  default:
    params = devParams;
}

export default params;

I'm trying to test this with the following code (not yet with assertions):

import params from '../../../parameters';
...

it.only('should return the appropriate config ', (done) => {
    process.env.APP_ENV = 'production';
    console.log(params);
    done();
});

However when I set environment variable process.env.APP_ENV as shown above it still reaches the module as undefined, so it always returns the development config instead of the production environment.

Setting aside the test part, the functionality is working fine, but I would like to test it regardless.

Any suggestions on how to fix this?

How to bypass assert in unit test with Catch framework?

In a test case I would like to test a function which in debug mode generates an assertion for invalid input. This unfortunately stops Catch test runner. Is there any way to bypass this assertion so that the test runner keeps going ?

Here is my test case:

 SCENARIO("Simple test case", "[tag]") {
    GIVEN("some object") {
        MyObject myobject;

        WHEN("object is initialized with invalid data") {
            // method init generates an assertion when parameters are invalid
            bool result = myObject.init(nullptr, nullptr, nullptr, nullptr);
            REQUIRE(false == result);

            THEN("data processing can't be started") {
            }
        }
    }
}

lundi 19 septembre 2016

How can I test that an MVVM light message has been received and acted upon?

I have a derived class that gets an object via property injection and registers on the messenger of that object:

public class Foo : AbsFoo
{
    private IBar bar;
    public override IBar Bar 
    {
        get {return bar;}
        set
        {
            bar = value
            if(bar != null)
            {
                bar.Messenger.Register<MyMessage>(this, m => SomeMethod());
            }
        }
    }
    public override void SomeMethod()
    {
        //..
    }
}

Basically, I want to set Bar, send a message, and verify that SomeMethod() is called.

My test looks like this:

var fixture = new Fixture();
fixture.Customize(new AutoConfiguredMoqCustomization());
var messenger = new Messenger();

var barFixture = fixture.Create<IBar>();
barFixture.Messenger = messenger

var fooMock = new Mock<Foo> {CallBase = true};
fooMock.SetupAllProperties();
fooMock.Object.Bar = barFixture;
fooMock.VerifySet(s=> s.Bar = It.IsAny<IBar>(),Times.AtLeastOnce()); // Success

messenger.Send(new MyMessage());
fooMock.Verify(c => c.SomeMethod(), Times.Once);  // Fails   

VerifySet() succeeds, and the correct object is passed in (checked via debugging), and the messenger instances are the same. But the Verifyon the method call fails, and I don't really understand why.

I'm not quite sure about the setup methods I have to use (Setup? SetupSet? Another?) on fooMock

pytest monkeypatch: it is possible to return different values each time when patched method called?

In unittest I can assert to side_effect iterable with values - each of them one-by-one will be returned when patched method called, moreover I found that in unittest my patched method can return different results according to input arguments. Can I make something like that in pytest? Documentation does not mention this.