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.

Can I and Should I test fireEvent and Handlers method in GWT?

I am writting test for gwt, but I did not found any example of fireEvent test. Can any one help me? I have event that has handler which put some current variable on the list. I would like to test the method that fires an event? Is this make any sens for You? Do You do such Unit tests? Please help.

Mocking an object for unit testing in Jasmine without using Require

I am trying to write specs for a JavaScript file (say 'functionality.js'). jQuery is the only external library used. I am using Karma as my test runner.

functionality.js in-turn refers to an object (say 'FOO') which is defined in a different file on which several methods are defined. The object FOO (and its methods) is used in several other files. I don't want to add in foo.js (where FOO is defined) to the list of files in Karma because that in turn makes use an object defined elsewhere and so on. I would like to be able to test functionality.js and others in isolation by mocking FOO as an empty object and be able to commonly use it in all my spec files. Would I be able to do that? Are there any other alternate patterns to this?

My trials: I tried creating a helper file and defined an empty FOO object wrapped in an IIFE, then added that file to Karma before I loaded my source JavaScript files, but it throws a ReferenceError saying can't find variable FOO in functionality.js:1

Use of undeclared identifier error in my case

My code invokes a C library function:

@implementation Store
  ...
  -(void) doWork {
    // this is a C function from a library
    int data = getData(); 
    ...
  }
end

I am unit testing the above function, I want to mock the C function getData() in my test, here is my test case:

@interface StoreTests : XCTestCase {
    int mData;
    Store *store;
}
@end

@implementation StoreTests

-(void) setUp {
  [super setUp];
   mData = 0;
   store = [[Store alloc] init];
}

-(void) testDoWork {
  // this call will use the mocked getData(), no problem here.
  [store doWork];
}

// mocked getData()
int getData() {
   mData = 10; // Use of undeclared identifier 'mData', why?
   return mData;
}

...
@end

Why I get complier error: Use of undeclared identifier 'mData' inside mocked getData() function?

Which level should I mock the dependency when the dependency is complicated?

Now I hava a class A to be tested. When I test a method(called Amethod) of A, Amethod will invoke another method(called Bmethod) of class B. And in this method of B, Bmethod will invoke a method of a interface C. It just likes a dependency tree:

A->B->C

I am using the gmock to do the unit test of Amethod of class A. Which one I should mock, B or C?

How to mock Abstract Class?

I'm mocking Abstract class but it gives an error that i can't instantiate the abstract class. I guess i'm missing some basics of mocking. So why can't i mock abstract class?

@Repository
    public abstract class AbstractAccountDaoImpl implements AccountDao{

        @Autowired
        SimpleJdbcCall simpleJdbcCall;

        @Override
        public List<Account> getAccounts(String id){
            SimpleJdbcCall simpleJdbcCall = getNewSimpleJdbcCall()
                    .withProcedureName(getAccountsProc)
                    .declareParameters(new SqlParameter("account_id", Types.VARCHAR));

                Object[] params = new Object[]  {id};
                simpleJdbcCall.returningResultSet("result", new AccountRowMapper());

                Map<String, Object> map = simpleJdbcCall.execute(params);

                return (List<Account>) map.get("result");

        }

Below is my junit:

public class AbstractAccountDaoImplTest  {

       private String IDS = "IDS";

    @InjectMocks
    private AbstractAccountDaoImpl abstractAccountDaoImpl;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldReturnAccounts() {
        Map<String, Object> map = new HashMap<>();

        map.put("result", Arrays.asList(new Account(), new Account()));

        simpleJdbcCallDefaultMock(simpleJdbcCallProvider, map);

        List<Account> resultList = abstractAccountDaoImpl.getAccounts(IDS);
        assertEquals(2, resultList.size());
    }

     public static void simpleJdbcCallDefaultMock(SimpleJdbcCallProvider simpleJdbcCallProvider, Map<String, Object> map) {
        SimpleJdbcCall simpleJdbcCall = Mockito.mock(SimpleJdbcCall.class);

        when(simpleJdbcCallProvider.getNewSimpleJdbcCall()).thenReturn(simpleJdbcCall);

        }

How can I mock this using Mockito? Or do i need to use something else to mock this? If I mock from mockito, it gives me an error cannot instantiate AbstractAccountDaoImpl.

Any advice?

Writing unit tests with omitting some methods inside a method and also some conditions on method being tested

How to write tests that escapes or bypasses few methods and conditions inside a big method that is being tested.

For example, I have this method below:

public bool IsValid(int id)
{

 var details = _myService.GetDetails(id); // This line should be avoided in test
 var doctorDetails = _myService.GetDoctorDetails("AUS"); // This needs to be executed

if(details.Name == "Ab") // This if I dont want to be part of my test
{
 // Do something

}

if(doctordetails !=null)
{
// Code to test

}
}

How to Mock RowMapper?

I'm trying to mock this dao and I'm getting a NPE. I'm not sure if I'm not mocking something correctly or I'm using something inappropriately. I have this dao below:

@Repository
public class PersonDaoImpl extends AbstractDao implements PersonDao {

    private static final String SQL = "select * from personTable";
    @Override
    public List<Person> getAllPerson() {
        PersonRowMapper personRowMapper = new PersonRowMapper ();
        List<Person> personList = getNamedParameterJdbcTemplate().query(SQL, personRowMapper);

        return personList ;
    }

And this is my junit

public class PersonDaoImplTest {

    @Mock
    protected NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Mock
    protected PersonRowMapper personRowMapper;

    @InjectMocks
    private PersonDaoImpl personDaoImpl;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldReturnPerson() {
        when(namedParameterJdbcTemplate.query(anyString(), Matchers.<RowMapper<PersonRowMapper>> any())).thenReturn(anyList());

        List<Person> resultList = personDaoImpl.getAllPerson();
        assertTrue(!resultList.isEmpty());
    }

It throws NPE on List<Person> resultList = personDaoImpl.getAllPerson();

What am I missing or not mocking correctly? Any help would be appreciated

Unit testing very simple functions

Say I have a simple function of the form:

def square(x):
    return x**2

If I write a unit test for testing correctness, is it considered bad practice to do something like:

def test_square(self):
        for _ in range(50):
            rand_num = random.uniform(-10,10)
            self.assertAlmostEqual(square(rand_num), x**2, msg= "Failed for input: {}".format(rand_num))

Where essentially instead of writing manual cases, I'm in a sense rewriting the function inside the unit test? Why or why won't this be considered good practice.

PS: I'm assuming there are other tests which check for invalid inputs and stuff, I'm asking this for the very specific case of testing correctness of the function.

Updating input html field from within an Angular 2 test

I would like to change the value of an input field from within an Angular 2 unit test.

        <input type="text" class="form-control" [(ngModel)]="abc.value" />

I can't just change the ngModel because 'abc' object is private:

 private abc: Abc = new Abc();

In Angular 2 testing, can I simulate the user typing into the input field so that the ngModel will be updated with what the user has typed from within a unit test?

I can grab the DebugElement and the nativeElement of the input field without a problem. (Just setting a the 'value' property on the nativeElement of the input field doesn't seem to work as it doesn't update the ngModel with what I've set for the value).

Maybe 'inputDebugEl.triggerEventHandler' can be called, but I'm not sure what arguments to give it so it will simulate the user having typed a particular string of input.

Thank you very much for your help!

How to unit test DataRow with a lot of columns in C#

What is the best way to unit test DataRows in C#?

I have a class architecture where all data is stored inside DataRow variable. How it works? For example when i double click on one record in the customers list the whole record from Customer table i loaded into _dataRow variable. The problem is that Customer table has over 200 columns.

The question is, do I need to manually create DataRow variable and fill all columns in every test method? Or maybe there is some mocking tool to mock all DataRow columns?

class Customer
{
    private DataRow _dataRow;

    public Customer(DataRow dataRow)
    {
        _dataRow = dataRow;
    }

    private string GetCustomerName()
    {
        return Convert.ToString(_dataRow["Name"]);
    }

    private string GetCustomerAddress()
    {
        return Convert.ToString(_dataRow["Street"]) + " " + Convert.ToString(_dataRow["House_No"]);
    }

    private int GetAge()
    {
        DateTime birthdate = Convert.ToDateTime(_dataRow["Birthdate"]);
        DateTime today = DateTime.Today;
        int age = today.Year - birthdate.Year;
        if (birthdate > today.AddYears(-age))
            age--;
        return age;
    }
}

proxyquire not stubbing method call

I'm trying to use proxyquire to replace a method call within a module I'm testing, but it is calling the method as is despite the fact I have the stub set up. What am I doing wrong?

formsReducer.test.js:

describe('Forms Reducer', () => {
    describe('types.UPDATE_PRODUCT', () => {
        it('should get new form blueprints when the product changes', () => {
            //arrange
            const initialState = {
                blueprints: [
                    {
                        id: 1,
                        categoryId: 1,
                        identifier: null,
                        name: "Investment Policy Statement",
                        sortGroup: 1,
                        wetSignRequired: false
                    }
                ]
            };
            const testBlueprints = [{ id: 999, categoryId: 1, name: "Form Blueprint Loaded From Product ID 1", sortGroup: 1, wetSignRequired: false }];
            //use proxyquire to stub call to formsHelper.getFormsByProductId 
            let formsReducer = proxyquire.noCallThru().load('./formsReducer', {
              formsHelper: {
                getFormsByProductId: id => { return testBlueprints }
              }
            }).default;
            const action = {
                type: types.UPDATE_PRODUCT,
                product: {
                    id: 1,
                    accountTypeId: 1,
                    officeRangeId: 1,
                    additionalInfo: "",
                    enabled: true
                },
            };
            //act
            const newState = formsReducer(initialState, action);
            //assert
            expect(newState.blueprints).to.be.an('array');
            expect(newState.blueprints).to.equal(testBlueprints);
        }); 
    });
});

formsReducer.js:

import * as types from '../constants/actionTypes';
import objectAssign from 'object-assign';
import initialState from './initialState';
import formsHelper from '../utils/FormsHelper';
export default function formsReducer(state = initialState.forms, action) {
  switch (action.type) {
    case types.UPDATE_PRODUCT: {
        let formBlueprints = formsHelper.getFormsByProductId(action.product.id);
        formBlueprints = formsHelper.addOrRemoveMnDisclosure(formBlueprints, action.stateOfResidence.id);
        return objectAssign({}, state, {blueprints: formBlueprints, instances: []});
    }
}

formsHelper.getFormsByProductId is not returning testBlueprints as it should if it were properly stubbed via proxyquire. What am I doing wrong?

AsserionError when testing two Pandas DataFrames

I am building a small test class to test a pandas heavy script. The script takes an xml file as input, however for my test class I made .data files out of the element attributes to easily load them in to a dict object.

class MetricsTest(TestCase):


    @classmethod
    def setUpClass(cls):
        def get_files(dir_path):
            return [join(dir_path, f)
                    for f in listdir(dir_path) if isfile(join(dir_path, f))]

        super(MetricsTest, cls).setUpClass()


        cls.data_files = ['p1-left-left', 'p2-left-right', 'p3-left-left','p4-left-right', 'p5-left-left', 'p6-left-right']

        file_name = 'TEST_p_stats.xml'
        file_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'test_files/games/{}'.format(
                file_name))

        dir_path = os.path.dirname(file_path)
        cls.files = get_files(dir_path)

        cls.metrics = Metrics(cls.files)
        #cls.metrics.run()
        cls.data = dict()
        xml = xml_parse(file_path)
        cls.xml = xml
        cls.df = dataframe_from_clusters(xml['p'])

    def setup_default_df(self):
        data = []
        for f in self.data_files:
            _data = []
            with open(os.path.join(
                    os.path.dirname(os.path.realpath(__file__)),
                    'test_files/games_data/{}.data'.format(f))) as _f:
                _data.append(dict(x.replace('\n','').split(None, 1) for x in _f))
            data.append(_data)
        return dataframe_from_clusters(data)

    def assertFrameEqual(self, df1, df2):
        """
        Assert that two dataframes are equal,
        ignoring ordering of columns"""
        return assert_frame_equal(df1.sort(axis=1), df2.sort(axis=1),
                                  check_names=True)

    def test_filter_df_no_direction(self):
        actual_df = self.df

        expected_df = self.setup_default_df()
        self.assertFrameEqual(expected_df, self.df)

However this gives me an error of

  File "das/src/testing.pyx", line 58, in pandas._testing.assert_almost_equal (pandas/src/testing.c:2758)
  File "das/src/testing.pyx", line 93, in pandas._testing.assert_almost_equal (pandas/src/testing.c:1843)
  File "das/src/testing.pyx", line 135, in pandas._testing.assert_almost_equal (pandas/src/testing.c:2527)
AssertionError: (very low values) expected 1.00000 but got 0.00000, with decimal 5

The code of dataframe_from_clusters function is

def dataframe_from_clusters(clusters):
    df = pd.DataFrame()

    for (idx, cluster) in enumerate(clusters):
        cluster_df = pd.DataFrame(cluster)
        cluster_df["cluster"] = idx
        df = pd.concat([df, cluster_df], ignore_index=True)

    return df

ZF2 Mock crashes on undefined method

I'm following this tutorial for unit testing on ZF2. I'm familiar with unit testing, so I pretty much understand what's going on.

I'm getting a PHP Fatal error: Call to undefined method Mock_AlbumTable_9fb22412::fetchAll() in [my controller's route here].

If I'm following correctly, the controller calls fetchAll on my mock object. The weird part is why is it undefined, if I declared it in the mock expectations.

My test code is exactly the same on the link provided, (Literally copy/pasted), and my AlbumTable class is also from the tutorial:

<?php

namespace Album\Model;

use Zend\Db\TableGateway\TableGateway;

class AlbumTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    // ... more code ...
}

What am I missing here?