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?

Unit Testing Swagger Output

We are using Swashbuckle to generate the swagger output for the REST endpoints of our MVC api application. I'm wondering what options there are for unit testing the swagger in a test project. I want to verify things like method names, descriptions, parameters etc etc to minimize the possibility that breaking changes can be introduced.

Thanks,

Avoid running function within Unit Test (NUnit)

Say I have a class:

public class SomeClass {

   public Model _model;

   public SomeClass() {
     _model = new Model(); 
   }

   public void Foo() {
     _model.DoSomethingHeavy();
   }

}

And a Test:

[TestFixture]
public class SomeClassTest {

  [Test]
  public void TestFooCalledSomethingHeavy() {
    SomeClass someClass = NSubstitute.Substitute.For<SomeClass>();  
    someClass.Foo();        
    someClass._model.Received().DoSomethingHeavy();
  }
}

I'm trying to test that someClass.Foo(); called _model.DoSomethingHeavy() but I don't actually want DoSomethingHeavy to run. How would I do that? Or is this the wrong approach?

I can't make ViewActions.closeSoftKeyboard() work in Espresso 2.2.2

I'm trying to test an app and I require to hide the keyboard, because I cannot click button because of it. So, I added Espresso in build.gradle:

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'

and tried to use this from android.support.test.espresso.action.ViewActions library:

ViewActions.closeSoftKeyboard();

Test runs successfully, but fails after typing some text in EditText in my layout. And keyboard is still there, showing.

P.S. I realized it was keyboard's fault after reading this answer.

Best API for loading test cases from excel sheet compatible with latest JUnit version

I have been looking up on various APIs which I can use with JUnit for reading test cases from excel sheet. I found easytest really nice to use but it's not compatible with JUnit 4.12. Other APIs that I found are not so easy to code as easy test. Can you recommend some of the APIs that I can use on my framework which is made on top of spring framework?

Thank You :)

Passing parameters to tearDown method

Suppose I have entity that creates SVN branch during its work. To perform functional testing I create multiple almost same methods (I use python unittest framework but question relates to any test framework):

class Tester(unittest.TestCase):

def test_valid1_url(self):
    url="valid1"
    BranchCreator().create_branch(url)
    self.assertUrlExists(url) # assume I have this method implemented

def test_valid2_url(self):
    url="valid2"
    BranchCreator().create_branch(url)
    self.assertUrlExists(url) # assume I have this method implemented

def test_invalid_url(self):
    url="invalid"
    self.assertRaises(ValueError, BranchCreator().create_branch, url)

After each test I want to remove the resulting branch or do nothing if test failed. Ideally I would use something like following:

@teardown_params(url='valid1')
def test_valid1_url(self):

def tearDown(self, url):
    if (url_exists(url)): remove_branch(url)

But tearDown does not accept any parameter. I see few quite dirty solutions:

a) create field "used_url" in Tester, set it in every method and use in tearDown:

def test_valid1_url(self):
    self.used_url="valid1"
    BranchCreator().create_branch(self.used_url)
    self.assertUrlExists(url) 
...
def tearDown(self):
    if (url_exists(self.used_url)): remove_branch(self.used_url)

It should work because (at least in my environment) all tests are run sequentally so there would be no conflicts. But this solution violates tests independency principle due to shared variable, and if I would manage to launch tests simultaneously, it will not work.

b) Use separate method like cleanup(self, url) and call it from every method

Is there any other approach?

Unit testing DefaultHttpRequestRetryHandler

I'm working on some legacy code that stores files to a remote server. I'd like to use Apache's DefaultHttpRequestRetryHandler to implement a retry logic. A simplified version of the implementation is shown below. How do I test my retry logic?

I was able to manually test it by overriding retryRequest() in the DefaultHttpRequestRetryHandler class but an automated way would be nice. (I'm using Spock to test.)

   private CloseableHttpClient getHttpClient() {
        DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler();
        CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(retryHandler).build();
        return httpClient;
   }

   public CloseableHttpResponse uploadFile(){    
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post, getHttpContext());
        } catch (Exception ex) {
            //handle exception
        }
        return response;    
   }

Unit test MEAN app with Jasmine newbie questions

I’m starting to learn Jasmine unit testing (i’m using Jasmine 2.5). Therefore I’m having little problem to understand some things and questions . What are good extensions for jasmine which will improve my work. How to test code like this

router.post('/user/login', function (req, res, next) {
  var data = {
    email: String,
    msg: String
  }
  console.log("In user/login:" + req.body.email + " " + req.body.password);

  if (Auth.isAlphaNumeric(req.body.password) && Auth.isEmailAddress(req.body.email)) {
    User.findOne({ email: { $regex: new RegExp("^" + req.body.email, "i") }, password: req.body.password }, function (err, doc) {

      if (doc) {
        data.msg = "AUTHORIZATION_SUCCESS";
        req.session.email = req.body.email;
        req.session.save();
      } else {
        data.msg = "AUTHORIZATION_FAILED";
      }

      res.send(JSON.stringify(data));
    })
  }
  else {
    data.msg = "AUTHORIZATION_FAILED";
    res.send(JSON.stringify(data));
  }
});

I have read that it is good pratice to dont get data from database but how to solve this problem with above example and what to do with session ?, add it somehow to spec or is there a better solution ?

With Jasmine can i test Angular 2 and TypeScript? If yes then is it hard ? do i need some tools to do this?

Rails 5: Refactoring - One to Many Relationship (Tests and Views)

Somewhat new to rails and trying to figure out some answers to questions I've been having with no real luck using the Rails Documentation or on the rails guides, or rails tutorials.

My goal is to embrace how rails handles things and try to make it easy for other developers to step into the project later.

Question 1: Refactoring Question

Rails practice in refactoring. I'm not sure if this should go in the model or the controller and really just want to know what items should go in the controller versus what should go in the model.

First Iteration :

<% @departments.each do |department| %>
      <tr>
        <td><%= department.name %></td>
        <td><%= department.description %></td>
        <td>
          <%= library = Library.find_by(id: department.library_id).name %>
        </td>
        <td><%= link_to 'Show', department %></td>
        <td><%= link_to 'Edit', edit_department_path(department) %></td>
        <td><%= link_to 'Destroy', department, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

This seemed wrong to me and seemed like that should be taken out of that part as backend logic.

Second Iteration:

Model

class Department < ApplicationRecord
  belongs_to :library

  def get_library_name(lib_id)
    library = Library.find_by(id: lib_id)
    return library.name
  end
end

View

<% @departments.each do |department| %>
      <tr>
        <td><%= department.name %></td>
        <td><%= department.description %></td>
        <td>
          <%= department.get_library_name(department.library_id) %>
        </td>
        <td><%= link_to 'Show', department %></td>
        <td><%= link_to 'Edit', edit_department_path(department) %></td>
        <td><%= link_to 'Destroy', department, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

This feels more correct, but not all the way there, so I'm not really sure how I can change it to be more correct, especially since the index view which lists out the records is very similar.

How should I refactor this?

Question 2: My Test Won't Pass

Either way, my test isn't passing. I'm guessing it is the way I'm using my one to many relationships.

  test "should get index" do
    get departments_url
    assert_response :success
  end

error:

DepartmentsControllerTest#test_should_get_index:
ActionView::Template::Error: undefined method `name' for nil:NilClass
    app/models/department.rb:6:in `get_library_name'
    app/views/admin/departments/index.html.erb:21:in `block in _app_views_admin_departments_index_html_erb__1894713831414342893_57284960'
    app/views/admin/departments/index.html.erb:16:in `_app_views_admin_departments_index_html_erb__1894713831414342893_57284960'
    test/controllers/departments_controller_test.rb:11:in `block in <class:DepartmentsControllerTest>'

Unit Testing for Extendscript

Need some guidance on automating unit testing for Extendscript..anyone have any experience running and writing unit tests on Adobe Extendscript jsx files with Grunt, Mocha, Chai, etc ?

Unit testing component with angulartics2 - Can't bind to 'angularticsCategory' since it isn't a known property of 'div'

I am starting a project using Angular 2.0.0 stable release created with angular-cli 1.0.0-beta.14 and angulartics 1.1.9.

I am trying to start some simple unit testing and am recording clicks on a button component

<div class="sidebar-toggle" (click)="toggleSideBar()" angulartics2On="click" angularticsCategory="">
   //divContent
</div>

However, when I run the test which is simple bootstrapping the component I get the error

Can't bind to 'angularticsCategory' since it isn't a known property of 'div'

The app works fine but the issue only comes up in testing. I can't find an example where someone is having the same error in testing. I know I am missing something like not properly exposing the angulartics2 lib in my karma.conf OR not injecting the Angulartics or a mocked dependency in my Testbed config.

Really lost and would like to know if anyone is having similar problems. Can provide more code snippets if needed but don't want to dump the whole file nobody's got time to read that!

GroovyMock misbehave

I will describe a weird (maybe wrong) behavior.

I have three classes:

class Foo {
    String foo

    public Foo(String foo) {
        this.foo = foo
    }
}

class Bar {
    String bar

    public Bar(String bar) {
        this.bar = bar
    }
}

class FooBar {
    private Foo foo
    private Bar bar

    public FooBar() {
        this.foo = new Foo("foo")
        this.bar = new Bar("bar")
    }

    public String printMe() {
        return "${foo.getFoo()} ${bar.getBar()}"
    }
}

I want to Test the FooBar class by catching constructors of dependencies classes Foo and Bar.

import com.scratch.Bar
import com.scratch.Foo
import com.scratch.FooBar
import spock.lang.Specification

import java.util.logging.Logger

public class Mockba extends Specification {
    Logger log = Logger.getLogger("")

    def "foo"() {
        given:

        GroovyMock(Foo, global: true)
        GroovyMock(Bar, global: true)
        Foo foo = GroovyMock(Foo)
        Bar bar = GroovyMock(Bar)

        when:

        FooBar fooBar = new FooBar()
        log.info("${fooBar.printMe()}")

        then:
        new Foo((String)_) >> foo
        new Bar((String)_) >> bar
        foo.getFoo() >> "oof"
        bar.getBar() >> "rab"
        assert 1 == 1 // That's fake
    }
}

The GroovyMock should catch the constructor call over Foo and Bar and supply the mocked version of these objects.

But unfortunately it seems that there is a weird thing that happen because when the instruction:

this.bar = new Bar("bar")

inside the FooBar() constructor is called. The GroovyMock returns the Foo mocked object. The debug watch over new Bar("") gives:

"Mock for type 'Foo' named 'foo'" as Mock result

That's a nonsense for me.

Any suggestion?

How to unit test a method that is dependent on another?

I have a React and Redux project I'm trying to unit test with Chai testing framework. Right now I'm writing a test for a reducer I have, and several of actions this reducer handles call helper methods. Here is an example:

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: []});
    }
  }
}

As you can see, if I test this method I'm dependent on the formsHelper.getFormsByProductId and formsHelper.addOrRemoveMnDisclosure methods to pass as well. How should I test this reducer/action? Should I make a separate set of test data that can be returned from these methods when a certain product.id is passed to these methods?

Setup byref parameters in VB from MOQ with C#

The code to be tested looks like this in VB. Simplified

Public Interface IFwCompressor
  Function Calculate(ByVal condenserPower As Double,
                     ByVal evaporatingTemp As Double,
                     ByVal condensingTemp As Double,
                     ByRef rotationalSpeed As Double,
                     ByRef compressorPower As Double,
                     ByRef electricalPower As Double) As CalculationResult

  Enum CalculationResult
    ActivateNextCircuit = 3
    Off = 2
    Ok = 0
    UnknownError = -1
    MaxRps = -6
  End Enum
End Interface

Public Class Compressor
  Private ReadOnly _fwCompressor As IFwCompressor

  Public Sub New(ByVal fwCompressor As IFwCompressor)
    _fwCompressor = fwCompressor                
  End Sub

  Public Function CalculateIntermittentResult(ByVal compressorInput As CompressorIntermittenInput) As StatusAndResult(Of CompressorStatus, CompressorResult)

    Dim meanCompressorPower, meanRotationalSpeed, meanElectricalPower As Double

    Dim result = _fwCompressor.CalculateIntermittentResult( _
      compressorInput.RotationalSpeed,
      compressorInput.RunningTimeFraction,
      compressorInput.CompressorPower,
      meanRotationalSpeed,
      meanCompressorPower,
      meanElectricalPower)

    Return New StatusAndResult(Of CompressorStatus, CompressorResult)(
      CompressorStatus.Ok,
      New CompressorResult(CompressorRunMode.Intermittent,
                           meanRotationalSpeed,
                           meanCompressorPower,
                           meanElectricalPower))
End Function

The test I've written like this. C# and the MOQ framework.

double meanRotationalSpeed = 15;
double meanCompressorPower = 1000; 
double meanElectricalPower = 500; 

fwCompressor.Setup(e => e.CalculateIntermittentResult(It.IsAny<double>(),
                                                      It.IsAny<double>(),
                                                      It.IsAny<double>(),
                                                      ref meanRotationalSpeed,
                                                      ref meanCompressorPower,
                                                      ref meanElectricalPower)).Returns(MaxRps);

My problem is that when the method gets invoke inside CalculateIntermittentResult, the parameters meanRotationalSpeed, MeanCompressorPower, MeanElectricalPower and the result return 0?

ByRef Parameters in MOQ, is it possible from C# to VB?

How to test Angular2 pipe in nodejs with mocha without karma

I'd like to be able to test an Angular2 pipe purely in nodejs environment without including karma etc.

It is possible to use typescript files as test suites for mocha

http://ift.tt/2dbCMDn

But when I have a import {Pipe} from '@angular/core' it gives me

/Users/foo/node_modules/@angular/core/src/util/decorators.js:173
        throw 'reflect-metadata shim is required when using class decorators';
        ^
reflect-metadata shim is required when using class decorators

Even if I write require('reflect-metadata') in my test file it still breaks with the same error.

Angular internally has this check:

(function checkReflect() {
    if (!(Reflect && Reflect.getMetadata)) {
        throw 'reflect-metadata shim is required when using class decorators';
    }
})();

And after requireing reflect-matadata I indeed have Reflect on the global object, however it still doesn't work...

Anyway is there a way to test an Angular pipe purley in nodejs with mocha?

I'm using webpack to bundle the app so the file I'm requring in my test file looks like this:

import {Pipe} from '@angular/core';

@Pipe({
    name: 'filterBy'
})

export class FilterByPipe {
  transform(items = [], prop, val) {
    return items.filter(someFilteringAlgorithm(prop, val));
  }
}

Angular2 "Final" Unit Test Override Directive

I am using Angular 2 Final, and using the TestBed for Unit tests

I have an issue when when using "overrideDirective" it seems that the actual directive is being called, as I am getting an error "No provider for Config!" which MyDirective that was replaced is dependent on.

Component View

  <div>
       <input myDirective>
       // some more logic etc...
  </div>

Directive to Replace

@Directive({
    selector: "myDirective"
})
class MyDirective{
    constructor(
        private config: Config
    ) {
    }
}

Spec File

@Component({
    template: "<my-component></my-component>"
})
class TestComponent{

}

@Directive({
    selector: "fake"
})
class FakeDirective {

}

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [
            MyComponent,
            MyDirective,
            TestComponent,
            FakeDirective
        ]
    });
});

beforeEach(async(() => {
    TestBed
        .overrideDirective(MyDirective, FakeDirective)
        .compileComponents();
    fixture = TestBed.createComponent(TestComponent);
}));

Any one encountered the issue and managed to fix it please?

Thanks

Is there an "assistant" for writing tests in Rails?

I would definitely like to write (more) tests for my projects. Unfortunately they often are a pain to setup, especially when a client needs rapid fixes/changes/results and there is no time to setup a test before coding.

Do you know of an assistant that helps setting up tests to make it more "fun"? Like a form you fill out and the assistant writes the whole FactoryGirl/Rspec-stuff?

Thanks for any ideas!

Unit testing a spring non - controller method using Java

Sample Code

Class Which is to be Mocked

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=RuntimeException.class)
@Repository
public class Sample {
    @Autowired
    SessionFactory sessionFactory;

    public Pdt loadpdtType(String planName) 
    {           
       Pdt pdt=new Pdt();

       System.out.println("I am called");
       Session session = sessionFactory.getCurrentSession();
       Query query = session.createQuery("From Dmaster where planName=:planName order by id")
                .setParameter("planName", planName);
       pList = query.list();

       pdt.setSI(pList.get(0).getSI());

       if(planName.equalsIgnoreCase("ABCD")
           pdt.setPDTType("xyz");
       else
           pdt.setPDTType("1234");
       return pdt;
   }

   public Resp getSeq(String Id,String type){
      Resp r=new Resp(Id,type);   
      return r;
   }

}

I need to call getpdtType() and getSeq() method from junit. My test Method is as follows

class SampleTester {

    @Autowired
    Sample samp;

    Pdt pdt;

    @Test
    public void Testt()     {
        try {
            samp=Mockito.mock(Sample.class);                
            Mockito.when(samp.loadpdtType("sampletext").thenCallRealMethod();
            pdt=samp.loadpdtType("sampletext");         
            Mockito.verify(samp).loadpdtType("sampletext");
            System.out.println("testresult:"+pdt.getPDTType());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

And The output is

I am called

java.lang.NullPointerException at com.docs.Sample.loadpdtType(Sample.java:58) [classes/:?] at com.docs.Sample$$EnhancerByMockitoWithCGLIB$$f5b2927b.CGLIB$loadpdtType$0() [mockito-core-1.10.19.jar:?] at com.docs.Sample.$$EnhancerByMockitoWithCGLIB$$f5b2927b$$FastClassByMockitoWithCGLIB$$15d15c8c.invoke() [mockito-core-1.10.19.jar:?] at org.mockito.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:216) [mockito-core-1.10.19.jar:?] at org.mockito.internal.creation.cglib.DelegatingMockitoMethodProxy.invokeSuper(DelegatingMockitoMethodProxy.java:19) [mockito-core-1.10.19.jar:?] at org.mockito.internal.invocation.realmethod.DefaultRealMethod.invoke(DefaultRealMethod.java:21) [mockito-core-1.10.19.jar:?] at org.mockito.internal.invocation.realmethod.CleanTraceRealMethod.invoke(CleanTraceRealMethod.java:30) [mockito-core-1.10.19.jar:?] at org.mockito.internal.invocation.InvocationImpl.callRealMethod(InvocationImpl.java:112) [mockito-core-1.10.19.jar:?] at org.mockito.internal.stubbing.answers.CallsRealMethods.answer(CallsRealMethods.java:41) [mockito-core-1.10.19.jar:?] at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34) [mockito-core-1.10.19.jar:?] at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91) [mockito-core-1.10.19.jar:?] at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29) [mockito-core-1.10.19.jar:?] at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38) [mockito-core-1.10.19.jar:?] at org.mockito.internal.creation.cglib.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:59) [mockito-core-1.10.19.jar:?] at com.docs.Sample$$EnhancerByMockitoWithCGLIB$$f5b2927b.loadpdtType() [mockito-core-1.10.19.jar:?] at com.documentation.SampleTester.Testt(SampleTester.java:31) [test-classes/:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_91] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_91] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_91] at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_91] at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12] at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12] at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12] at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) [junit-4.12.jar:4.12] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12] at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:?]

How to mock $window.Notification

I am still learning the ropes when it comes to unit testing with angular. I have an angular service that I use to create HTML5 notifications. Code is similar to the following:

(function() {
  'use strict';

  angular
    .module('blah')
    .factory('OffPageNotification', offPageNotificationFactory);

  function offPageNotificationFactory($window) {
    //Request permission for HTML5 notifications as soon as we can
    if($window.Notification && $window.Notification.permission !== 'denied')     {
      $window.Notification.requestPermission(function (status) { });
    }

    function OffPageNotification () {
      var self = Object.create(OffPageNotification.prototype);
      self.visibleNotification = null;
      return self;
    }


 OffPageNotification.prototype.startNotification = function (options) {
      var self = this;
      self.options = options;
      if(self.options.showHtml5Notification && (!self.options.onlyShowIfPageIsHidden || $window.document.hidden)) {
    if($window.Notification && $window.Notification.permission !== 'denied')     {
          self.visibleNotification = new $window.Notification('Notification',     {
              body: self.options.notificationText,
              icon: self.options.notificationIcon
            });
        }
      }
    };

    .
    .
    .
  return new OffPageNotification();
  }
})();

I am attempting to write unit tests for this but am unsure how to mock $window.Notification so it can be used as both a constructor...

self.visibleNotification = new $window.Notification(....)

and also contain properties

if($window.Notification && $window.Notification.permission !== 'denied')

and methods....

$window.Notification.requestPermission(

An example of something I have tried is:

     describe('startNotification', function() {

     beforeEach(function() {
       var mockNotification = function (title, options) {
         this.title = title;
         this.options = options;
         this.requestPermission = sinon.stub();
       };

       mockNotification.prototype.permission = 'granted';

       mockWindow = {
         Notification: new mockNotification('blah', {}),
         document: {hidden: true}
       };

       inject(function (_OffPageNotification_) {
         OffPageNotification = _OffPageNotification_;
       });
     });

     it('should display a html5 notification if the relevant value is true in the options, and permission has been granted', function(){
       var options = {
         showHtml5Notification: true,
         onlyShowIfPageIsHidden: true
       };
       OffPageNotification.startNotification(options);
     });
  });

I get an error saying '$window.Notification is not a constructor' with this setup and I understand why (I am passing in an instantiated version of the mockNotification). But if I set mockWindow.Notification = mockNotification then I get an error when it calls requestPermission since this is undefined.

Any help is appreciated

In sailsJS test POST request from Supertest not hitting function defined for route

My Project is on SailsJS. I am not using SailsJS Model. Data Controller is defined in /api/DataController. The routes to the Data Controllers are defined in config/routes.js. I am testing Data Controllers using Supertest.

The problem I am facing is when I test GET call to my route /api/1/drives the function works but when I do POST or PUT request to the route the corresponding functions in the Data Controller is not getting called. Everything is working fine with client.

it('it should edit drive details', function (done) {
  var ids = { 'ids': [1, 2, 3]}
  var editMap = {class: "Drives"}
  try {
    server
      .put('/api/1/drives')
      .send({driveIds, editMap})
      .expect(200, done());
  } catch (err) {
    done(err);
  }
}

And the route is defined in config/routes.js:

'put /api/1/drives': {
  controller: 'DataController',
  action: 'editDrives'
}

I have checked after removing the promises and other settings as well.

I am attempting to use Junit, mockito and PowerMock to create a unit test

I am attempting to use Junit, mockito and PowerMock to create a unit test

My problem is that one of the classes which i am attempting to mock is returning a null object

This is my code

    @RunWith(PowerMockRunner.class)
@PrepareForTest(ClientBuilder.class)
public class SolrPopulateApplicationTest {

   @Mock
   ClientConfig clientConfig;

   @Mock
   Client client;

   @Mock
   Response response;

   @Mock
   JerseyClient jerseyClient;

   @Mock (answer = Answers.RETURNS_DEEP_STUBS)
   JerseyWebTarget jerseyWebTarget;

   @InjectMocks
   @Autowired
   SolrPopulateApplication solrPopulateApplication;

   @Test
   public void indexTest(){

       PowerMockito.mockStatic(ClientBuilder.class);

       ClientBuilder cli = Mockito.mock(ClientBuilder.class);

    when(ClientBuilder.newClient(Matchers.any())).thenReturn(client);

       when(jerseyClient.target(Matchers.anyString())).thenReturn(jerseyWebTarget);

       when(jerseyWebTarget.path(Matchers.anyString())
               .queryParam(Matchers.anyString(),Matchers.anyString())
       .request(Matchers.anyString())
               .header(Matchers.anyString(),Matchers.anyString())
       .post(Matchers.any())).thenReturn(response);

       boolean var = solrPopulateApplication.index("test","test");

   }
}

When a debug breakpoint is placed after all the mocks should have been setup i get the following

    client = {Client$$EnhancerByMockitoWithCGLIB$$7f4c6946@1705} "client"
response = {Response$$EnhancerByMockitoWithCGLIB$$b85fdf42@1704} "response"
jerseyWebTarget = {JerseyWebTarget$$EnhancerByMockitoWithCGLIB$$7d7091b9@1703} "null"
solrPopulateApplication = {SolrPopulateApplication@1702} 
jerseyClient = {JerseyClient$$EnhancerByMockitoWithCGLIB$$6437ba91@1701} "jerseyClient"
cli = {ClientBuilder$$EnhancerByMockitoWithCGLIB$$20196b6d@1700} "Mock for ClientBuilder, hashCode: 2080643905"
this = {SolrPopulateApplicationTest@1695}

as you can see the jerseyWebClient is a NULL and this is causing a nullpointerexception when i try to run the test.

I have tried removing (answer = Answers.RETURNS_DEEP_STUBS) from the @mock statement and this makes no difference.

The method being tested actually calls a interface which implements the JerseyWebTarget class. I have made sure I am trying to mock the right class by putting a debugger in the JerseyWebTarget class to make sure its stopping on the method which is being called via the interface.

can anyone tell me why this is happening and how to fix it.

Istanbul jasmine-node issue on Windows 7

Trying to run istanbul with jasmine-node

Running: node C:\myproject\project1\node_modules.bin\jasmine-node.CMD test No coverage information was collected, exit without writing coverage information C:\myproject\project1\merg\node_modules.bin\jasmine-node.CMD:1 (function (exports, require, module, __filename, __dirname) { @IF EXIST "%~dp0\node.exe" ( ^ SyntaxError: Invalid or unexpected token at Object.exports.runInThisContext (vm.js:76:16) at Module._compile (module.js:528:28) at Object.Module._extensions..js (module.js:565:10) at Object.Module._extensions.(anonymous function) [as .js] (C:\myproject\project1\merg\node_modules\istanbul\lib\hook.js:109:37) at Module.load (module.js:473:32) at tryModuleLoad (module.js:432:12) at Function.Module._load (module.js:424:3) at Function.Module.runMain (module.js:590:10) at runFn (C:\myproject\project1\merg\node_modules\istanbul\lib\command\common\run-with-cover.js:122:16) at C:\myproject\project1\merg\node_modules\istanbul\lib\command\common\run-with-cover.js:251:17

npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Users\itsme\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "run" "test-cov" npm ERR! node v6.6.0 npm ERR! npm v3.10.7 npm ERR! code ELIFECYCLE npm ERR! Merg@0.4.0 test-cov: istanbul cover --report cobertura --include-all-sources jasmine-node test npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the Merg@0.4.0 test-cov script 'istanbul cover --report cobertura --include-all-sources jasmine-node test'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the Merg package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! istanbul cover --report cobertura --include-all-sources jasmine-node test npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs Merg npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls Merg npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request: npm ERR! C:\myproject\project1\merg\npm-debug.log

Mvx.Resolve fails in unit tests

I'm currently trying to write unit tests for an android/ios application written in xamaring using mvvmcross. I've followed the instructions in the wiki and they do work well to the point when a service tries to change the ViewModel this way:

var viewDispatcher = Mvx.Resolve<IMvxViewDispatcher>();
viewDispatcher?.ShowViewModel(
new MvxViewModelRequest(typeof(HomeViewModel), null, null, MvxRequestedBy.Unknown));

The tests fail at the first line with Mvx.Resolve();. I assume this is down to registering the interfaces in the mock IoC container:

this.mockDispatcher = new MockDispatcher();
this.Ioc.RegisterSingleton<IMvxViewDispatcher>(this.mockDispatcher);
this.Ioc.RegisterSingleton<IMvxMainThreadDispatcher(this.mockDispatcher);

so Mvx cannot resolve then when called this way. Can this code be tested or is there any other possibility to change the ViewModel from the service?

Issue with getting unit test to pass involving DOM

I am not sure why the DOM element that I try to create in my unit test always return either undefined or null. I need the DOM element to attach the event listener to it. I am using Mocha and Chai to do my client side Javascript testing.

I have written the following test:

  it('should change the isClick value when a click event occurs', function() {
      let target = document.createElement('span');
      let isClick = false;

      testFunction(target, isClick);
      target.dispatchEvent(new Event("click")); // code here does not work since target is either undefined or null

      chai.assert.isTrue(isClick, "isClick should now be true");
    });

The testFunction looks like this:

    function testFunction(target, isClick) {
      target.addEventListener("click", (e) => {
         isClick = !isClick;
      });
    }

I am not sure if I am suppose to create a spy or stub for the DOM element, can someone give me pointers on how I should approach a test case like this?

Angular2 unit tests. 'Npm test' runs successfully only once and never again

I'm trying to setup unit test for my Angular2 project following the directions here: http://ift.tt/2dbCjkl Using this project first time I run npm test everything works fine. Than I press ctrl-c to stop testing session. Next time I execute npm test without any changes to the project it fails with the following error:

[1] Chrome 53.0.2785 (Windows 10 0.0.0) LOG: Error{originalErr: Error{}}
[1]
    Chrome 53.0.2785 (Windows 10 0.0.0): Executed 0 of 4 SUCCESS (0 secs / 0 secs)
[1] Missing error handler on `socket`.
[1] TypeError: Cannot set property '49007121' of null
[1]     at createHtmlResults (C:\Projects\Tmp\ng-karma-test\node_modules\karma-htmlfile-reporter\index.js:57:32)
[1]     at initializeHtmlForBrowser (C:\Projects\Tmp\ng-karma-test\node_modules\karma-htmlfile-reporter\index.js:78:5)
[1]     at HTMLReporter.onBrowserStart (C:\Projects\Tmp\ng-karma-test\node_modules\karma-htmlfile-reporter\index.js:91:5)
[1]     at Server.<anonymous> (C:\Projects\Tmp\ng-karma-test\node_modules\karma\lib\events.js:13:22)
[1]     at emitTwo (events.js:111:20)
[1]     at Server.emit (events.js:191:7)
[1]     at Browser.onStart (C:\Projects\Tmp\ng-karma-test\node_modules\karma\lib\browser.js:126:13)
[1]     at Socket.<anonymous> (C:\Projects\Tmp\ng-karma-test\node_modules\karma\lib\events.js:13:22)
[1]     at emitOne (events.js:101:20)
[1]     at Socket.emit (events.js:188:7)
[1]     at Socket.onevent (C:\Projects\Tmp\ng-karma-test\node_modules\socket.io\lib\socket.js:335:8)
[1]     at Socket.onpacket (C:\Projects\Tmp\ng-karma-test\node_modules\socket.io\lib\socket.js:295:12)
[1]     at Client.ondecoded (C:\Projects\Tmp\ng-karma-test\node_modules\socket.io\lib\client.js:193:14)
[1]     at Decoder.Emitter.emit (C:\Projects\Tmp\ng-karma-test\node_modules\component-emitter\index.js:134:20)
[1]     at Decoder.add (C:\Projects\Tmp\ng-karma-test\node_modules\socket.io-parser\index.js:247:12)
[1]     at Client.ondata (C:\Projects\Tmp\ng-karma-test\node_modules\socket.io\lib\client.js:175:18)
    Chrome 53.0.2785 (Windows 10 0.0.0) ERROR
[1]   Disconnectedundefined
    Chrome 53.0.2785 (Windows 10 0.0.0): Executed 0 of 4 DISCONNECTED (5.004 secs / 0 secs)
[1] 18 09 2016 18:34:21.946:ERROR [karma]: TypeError: Cannot read property '49007121' of null
[1]     at HTMLReporter.onBrowserComplete (C:\Projects\Tmp\ng-karma-test\node_modules\karma-htmlfile-reporter\index.js:95:23)
[1]     at Server.<anonymous> (C:\Projects\Tmp\ng-karma-test\node_modules\karma\lib\events.js:13:22)
[1]     at emitOne (events.js:101:20)
[1]     at Server.emit (events.js:188:7)
[1]     at Timeout._onTimeout (C:\Projects\Tmp\ng-karma-test\node_modules\karma\lib\browser.js:166:17)
[1]     at tryOnTimeout (timers.js:232:11)
[1]     at Timer.listOnTimeout (timers.js:202:5)
[1] karma start karma.conf.js exited with code 1

The number in quotes is different every time. If I reboot my PC the unit test runs again but also only one time and than the same error again.

Thanks.

PS: Bringing all packages to the latest version gives the following errors: node_modules/@types/jasmine/index.d.ts(73,9): error TS2375: Duplicate number index signature. node_modules/@types/jasmine/index.d.ts(127,9): error TS2374: Duplicate string index signature. node_modules/@types/node/index.d.ts(99,6): error TS2300: Duplicate identifier 'BufferEncoding'. node_modules/@types/node/index.d.ts(544,26): error TS2300: Duplicate identifier 'Buffer'. node_modules/@types/node/index.d.ts(544,50): error TS2300: Duplicate identifier 'SlowBuffer'. node_modules/@types/node/index.d.ts(565,18): error TS2300: Duplicate identifier 'EventEmitter'. node_modules/@types/node/index.d.ts(724,18): error TS2300: Duplicate identifier 'Agent'. node_modules/@types/node/index.d.ts(769,18): error TS2300: Duplicate identifier 'Worker'. node_modules/@types/node/index.d.ts(1070,18): error TS2300: Duplicate identifier 'Script'. node_modules/@types/node/index.d.ts(1912,18): error TS2300: Duplicate identifier 'TLSSocket'. node_modules/@types/node/index.d.ts(2203,18): error TS2300: Duplicate identifier 'Stream'. node_modules/@types/node/index.d.ts(2214,18): error TS2300: Duplicate identifier 'Readable'. node_modules/@types/node/index.d.ts(2237,18): error TS2300: Duplicate identifier 'Writable'. node_modules/@types/node/index.d.ts(2255,18): error TS2300: Duplicate identifier 'Duplex'. node_modules/@types/node/index.d.ts(2276,18): error TS2300: Duplicate identifier 'Transform'. node_modules/@types/node/index.d.ts(2298,18): error TS2300: Duplicate identifier 'PassThrough'. node_modules/@types/node/index.d.ts(2369,5): error TS2300: Duplicate identifier 'export='. node_modules/@types/node/index.d.ts(2391,18): error TS2300: Duplicate identifier 'Domain'. typings/globals/node/index.d.ts(78,6): error TS2300: Duplicate identifier 'BufferEncoding'. typings/globals/node/index.d.ts(516,9): error TS2502: 'BuffType' is referenced directly or indirectly in its own type annotation. typings/globals/node/index.d.ts(517,9): error TS2502: 'SlowBuffType' is referenced directly or indirectly in its own type annotation. typings/globals/node/index.d.ts(518,26): error TS2300: Duplicate identifier 'Buffer'. typings/globals/node/index.d.ts(518,50): error TS2300: Duplicate identifier 'SlowBuffer'. typings/globals/node/index.d.ts(539,18): error TS2300: Duplicate identifier 'EventEmitter'. typings/globals/node/index.d.ts(698,18): error TS2300: Duplicate identifier 'Agent'. typings/globals/node/index.d.ts(743,18): error TS2300: Duplicate identifier 'Worker'. typings/globals/node/index.d.ts(1044,18): error TS2300: Duplicate identifier 'Script'. typings/globals/node/index.d.ts(1886,18): error TS2300: Duplicate identifier 'TLSSocket'. typings/globals/node/index.d.ts(2177,18): error TS2300: Duplicate identifier 'Stream'. typings/globals/node/index.d.ts(2188,18): error TS2300: Duplicate identifier 'Readable'. typings/globals/node/index.d.ts(2211,18): error TS2300: Duplicate identifier 'Writable'. typings/globals/node/index.d.ts(2229,18): error TS2300: Duplicate identifier 'Duplex'. typings/globals/node/index.d.ts(2250,18): error TS2300: Duplicate identifier 'Transform'. typings/globals/node/index.d.ts(2272,18): error TS2300: Duplicate identifier 'PassThrough'. typings/globals/node/index.d.ts(2343,5): error TS2300: Duplicate identifier 'export='. typings/globals/node/index.d.ts(2365,18): error TS2300: Duplicate identifier 'Domain'. npm ERR! Test failed. See above for more details.

Boost Unit Testing a move constructor?

I have this code here:

template <typename T>
sorted_vector<T>& sorted_vector<T>::operator = ( sorted_vector<T> && src ) {
    delete [] beg_;

beg_ = src.beg_;
end_ = src.end_;
cap_ = src.cap_;

src.beg_ = nullptr;
src.end_ = nullptr;
src.cap_ = nullptr;

return *this;
}

If I am trying to unit test this using the boost library, how can I compare the original location of the vector, and the new "moved to" location?

How can I use Moq to test my Index action that returns list from the database?

I am learning to use unit testing and Moq for ASP.NET MVC 5. I am trying to write my first unit test for the index action of one of my controllers.

Here is the code for the index action.

[Authorize]
public class ExpenseController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: /Expense/
    public ActionResult Index()
    {
        return View(db.Expenses.ToList().Where(m => m.ApplicationUserId == User.Identity.GetUserId()));
    }
}

All I want to do is just check that the returned view is not null

Something like this

    [TestMethod]
    public void ExpenseIndex()
    {
        // Arrange
        ExpenseController controller = new ExpenseController();

        // Act
        ViewResult result = controller.Index() as ViewResult;

        // Assert
        Assert.IsNotNull(result);
    }

Of course, this is not working because of the connecting to the database and the using of the ApplicationUserId so would you guys help me to moq and unit test this action or recommend me a tutorial where I can get familiar with mocking in ASP.NET MVC.

Nunit Test fails with Exceptions even when ExpectedException attribute is there

I have this simple test

 [Test]
 [ExpectedException(typeof(Exception))]
 public void Test2()
 {
     throw new Exception();
 }

as I knew this test shoudln't be failed because I am expcted to see such an exception, but it fails with this error

Test Name:  Test2
Test FullName:  Framework.Tests.Service.BaseServiceTest.Test2
Test Source:    c:\Framework.Tests\Service\BaseServiceTest.cs : line 75
Test Outcome:   Failed
Test Duration:  0:00:00.189

Result StackTrace:  at Framework.Tests.Service.BaseServiceTest.Test2() in c:\Framework.Tests\Service\BaseServiceTest.cs:line 76
Result Message: System.Exception : Exception of type 'System.Exception' was thrown.

I have tried with other types of exceptions too, and result is the same

Unit test controller

I make an ionic app and it finish but when i start to add tests to it I face a problem with $resources ,in this case I have this Controller :

  .controller('newAccountCtrl', function($scope, $window, $rootScope, API, $ionicPopup, $state) {
    $scope.newData = {};
    $scope.$on('$ionicView.enter', function() {

        $scope.newData = {};
    });
    $scope.newInfo = function() {
        API.newAccountInfo().update({ restCode: $scope.newData.restore_code }, $scope.newData, function(res, header) {
            $rootScope.popup('success', "OKAY");
            $window.location.href = '#/login';
        }, function(err) {
            if (err.data == null)
                $rootScope.popup("Error", "no connection");
            else
                $rootScope.popup('error', err.data.error);
        });
    }
})

and in the service i make a request using $resources in function :

angular.module('starter.services', [])
.factory('API', function($rootScope, $resource, $ionicPopup, $ionicLoading, $window) { return {
          newAccountInfo: function() {
            return $resource(base + '/restoreinfo/:restCode', { restCode: '@_restCode' }, {
                update: {
                    method: 'PUT'
                }
            }, {
                stripTrailingSlashes: false
            });
        }}});

and in the my test the following code:

describe('newAccountCtrl', function() {

var controller,
    deferredLogup, scope, $q;
beforeEach(angular.mock.module('starter'));
// TODO: Load the App Module
beforeEach(module('starter.controllers'));
beforeEach(module('starter.services'));

// TODO: Instantiate the Controller and Mocks
beforeEach(inject(function($controller, _$q_, $rootScope, _API_) {
    $q = _$q_;
    scope = $rootScope.$new();
    API = _API_;

    spyOn(API, 'newAccountInfo').and.callThrough(function(callback) {
        deferredLogup.promise.then(callback);
        return { $promise: deferredLogup.promise };
    });

    controller = $controller('newAccountCtrl', {
        '$scope': scope,
        API: API
    });

}));
it('#newAccountInfo', function() {

    scope.newInfo();

    expect(API.newAccountInfo.update).toHaveBeenCalled();

})   });

but I get the error :

Expected a spy, but got undefined.

What I misunderstand here, the code work perfect

Generating list of lists with custom value limitations with Hypothesis

The Story:

Currently, I have a function-under-test that expects a list of lists of integers with the following rules:

  1. number of sublists (let's call it N) can be from 1 to 50
  2. number of values inside sublists is the same for all sublists (rectangular form) and should be >= 0 and <= 5
  3. values inside sublists cannot be more than or equal to the total number of sublists. In other words, each value inside a sublist is an integer >= 0 and < N

Sample valid inputs:

[[0]]
[[2, 1], [2, 0], [3, 1], [1, 0]]
[[1], [0]]

Sample invalid inputs:

[[2]]  # 2 is more than N=1 (total number of sublists)
[[0, 1], [2, 0]]  # 2 is equal to N=2 (total number of sublists)

I'm trying to approach it with property-based-testing and generate different valid inputs with hypothesis library and trying to wrap my head around lists() and integers(), but cannot make it work:

  • the condition #1 is easy to approach with lists() and min_size and max_size arguments
  • the condition #2 is covered under Chaining strategies together
  • the condition #3 is what I'm struggling with - cause, if we use the rectangle_lists from the above example, we don't have a reference to the length of the "parent" list inside integers()

The Question:

How can I limit the integer values inside sublists to be less than the total number of sublists?


Some of my attempts:

from hypothesis import given
from hypothesis.strategies import lists, integers

@given(lists(lists(integers(min_value=0, max_value=5), min_size=1, max_size=5), min_size=1, max_size=50))
def test(l):
    # ...

This one was very far from meeting the requirements - list is not strictly of a rectangular form and generated integer values can go over the generated size of the list.

from hypothesis import given
from hypothesis.strategies import lists, integers

@given(integers(min_value=0, max_value=5).flatmap(lambda n: lists(lists(integers(min_value=1, max_value=5), min_size=n, max_size=n), min_size=1, max_size=50)))
def test(l):
    # ...

Here, the #1 and #2 are requirements were being met, but the integer values can go larger than the size of the list - requirement #3 is not met.

Soft lenient recursive assertion tool like Unitils' ReflectionAssert

Does somebody know a tool with functionality like Unitils' ReflectionAssert::assertLenientEquals, but such, that allows soft assertion?

dimanche 18 septembre 2016

'Karma', 'Jasmine 'module is not defined [AngularJs Testing]

I searched all post on SO for this topic but none solve my problem. I try to test my filter but i get error that module is not defined. I included my angular-mock file i karma config and i have all depend ices in right order. Can anyone see the reason for such behavior from my code below?

TEST

describe('filter', function() {

beforeEach(angular.mock.module('myApp'));

 describe('reverse', function () {
   it('should reverse string', inject(function (reverse) {
       expect(reverse("ABC")).toEqual('BCA');
      }))
      })
     });

Karma.config

// Karma configuration


  module.exports = function(config) {
   config.set({

    // base path that will be used to resolve all patterns (eg. files,   exclude)
    basePath: '',


   // frameworks to use
  // available frameworks: http://ift.tt/1ft83uu
    frameworks: ['jasmine'],


   // list of files / patterns to load in the browser
    files: [
    'app/js/vendor/angular.min.js',
    'app/js/vendor/angular-mock.js',
    'app/js/angular.module.js',
    'app/js/angular.module.spec.js'
     ],


// list of files to exclude
exclude: [
],

 }

How does JUnit find tests?

I had assumed that JUnit found tests (inside classes derived from junit.framework.TestCase) by looking for methods annotated with @Test. However, I've included a test from http://ift.tt/2cVdRaL in a project. The structure of the code is as follows:

import junit.framework.TestCase;

public class JenkinsHashTest extends TestCase {
    public void testHashes() {
        ...//this code is run
    }   
}

I have confirmed that the test method testHashes() is run despite not being annotated with @Test. In case it's relevant, I'm invoking all of this via gradle test.

How to test node.js-mongodb app using Mocha, Chai and Sinon? I am having difficulty with Sinon part

I am new to testing and having difficulty with Sinon stubs and mocks.

Here is the routes file : quotes.js

const express = require('express');
const request = require('request');
const async = require('async');
const validator = require('validator');

const quote_router = express.Router();

const confg = require("../../confg/confg");
const quote = require("../models/mquotes");
const quotes_model = quote.quotes;

// host name - needs to be set up using the environment variable
const hostname = confg.hostname;

// route for "quotes/"
quote_router.route("/")
// get route : display the random quote
.get((req, res) => {
    // display random quote
    async.waterfall([
            (callback) => {callback(null, {res});},
            quote.count_quotes
        ], check_quote_exist
    );
})
// post route : create a new quote
.post((req, res) => {
    const doc_json = {author : validator.escape(req.body.quote_author), quote_text : validator.escape(req.body.quote_text)};
    const params = {res, doc_json, quote_action : quote.create_quote};
    add_edit_quote(params);
})
// put route : edit the quote
.put((req, res) => {
    const doc_json = {author : validator.escape(req.body.quote_author), quote_text : validator.escape(req.body.quote_text)};
    const params = {res, doc_json, quote_action : quote.update_quote, qid : req.body.quote_id};
    add_edit_quote(params);
})
// delete quote : delete the quote
.delete((req, res) => {
    const qid = req.body.qid;
    const condition = {_id : qid};
    async.waterfall([
            (callback) => {callback(null, {res, condition});},
            quote.delete_quote
        ], request_quote_list
    );
});

// route for "quotes/list" : display quotes list
quote_router.get("/list/", (req, res) => {
    // mention the main operation 
    let operation;

    if(req.body.operation != 'undefined') {
        operation = req.body.operation;
    } else {
        operation = "list_quotes";
    }

    async.waterfall([
            (callback) => {callback(null, {res, operation});},
            quote.list_quote
        ], display_quotes_list
    );
});
// display the quotes list
const display_quotes_list = (err, params, quotes_list) => {
    if (err) {return console.log(err);}

    const res = params.res;
    const operation = params.operation;
    const header_msg = "List of all the quotes";
    let alert_msg;

    if(operation == "list_quotes")  {
        alert_msg = null;
    } else if(operation == "delete_quote")  {
        alert_msg = "Quote has been deleted";
    }

    const params_out = {
        page: "quote_list",
        title: 'Quotes Manager',
        host: hostname,
        header_msg,
        alert_msg,
        quotes_list
    };
    res.render('index', params_out);
};

// send http request for quote list page
const request_quote_list = (err, params) => {
    if (err) {return console.log(err);}

    const res = params.res;
    const operation = "delete_quote";

    request.get('http://' + hostname + '/quotes/list/', {json:{operation}},
        (error, response, body) => {
            if (!error && response.statusCode == 200) {
                res.send(body);
            }
    });
};

module.exports = quote_router;

This is not complete file. I have included only a portion of it.

And her is the model file : mquotes.js

const mongoose = require('mongoose');

// Define quote schema
const quoteSchema = new mongoose.Schema({
    author: String,
    quote_text: {type: String, required: true}
    },
    {timestamps: true}
);
const quote = {};

// Define quotes model
quote.quotes = mongoose.model('quotes', quoteSchema);

// error handler 
error_handler = (callback, err, params, return_value) => {
    if(err) { return callback(err);}
    else {callback(null, params, return_value);}
};

// add quote - create
quote.create_quote = (params, callback) => {
    const res = params.res;
    const doc_json = params.doc_json;
    quote.quotes.create(doc_json, (err, quotes_detail) => {
        error_handler(callback, err, {res, operation : 'create_quote'}, quotes_detail);
    });
};

// count the number of quotes
quote.count_quotes = (params, callback) => {
    quote.quotes.count({}, (err, quotes_count) => {
        error_handler(callback, err, params, quotes_count);
    });
};

// delete quote - delete - id
quote.delete_quote = (params, callback) => {
    quote.quotes.remove(params.condition, (err, query) => {
        error_handler(callback, err, params);
    });
};

// list quote - find
quote.list_quote = (params, callback) => {
    quote.quotes.find({}, (err, quotes_list) => {
        error_handler(callback, err, params, quotes_list);
    });
};

// find quote by id
quote.quote_by_id = (params, callback) => {
    quote.quotes.findById(params.qid, (err, quotes_detail) => {
        error_handler(callback, err, params, quotes_detail);
    });
};

// returns the detail of random quote
quote.random_qoute = (params, callback) => {
    const random_number = params.random_number;

    // select one quote after skipping random_number of times
    quote.quotes.findOne({}, (err, quotes_detail) => {
        error_handler(callback, err, params, quotes_detail);
    }).skip(random_number);
};

// update quote - update - id
quote.update_quote = (params, callback) => {
    const options = {new: true};
    const qid = params.qid;
    const update_json = params.doc_json;

    quote.quotes.findByIdAndUpdate(qid, {$set: update_json}, options, (err, quotes_detail) => {
        params.operation = 'update_quote';
        error_handler(callback, err, params, quotes_detail);
    });
};

module.exports = quote;

I have installed mocha globally. Now, I want to test the model. Lets take the quote.list_quote function for example.

const mongoose = require('mongoose');
const chai = require('chai');
const sinon = require('sinon');

const expect = chai.expect; // use the "expect" style of Chai
const mquotes = require('./../../app/models/mquotes');

describe('Tests for quote models', () => {
    describe("List quote", () => {
        it('list_quote() should return list of quotes', () => {

        });
    });
});

Can anyone tell me about my coding practice too. I mean the way I use functions and modules.

What is the relationship between junit ,testng ,mockito ,easymock and PowerMock?

I'm confused with these stuff and i heard that junit and testng are the layer1, easymock and mockito are layer2 based on layer1 , and powermock is based on layer2. Is it correct?

samedi 17 septembre 2016

Time function conversion output JavaScript Syntax and Approach

The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds.

The resulting expression is made of components like 4 seconds, 1 year, etc. In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1.

The components are separated by a comma and a space (", "). Except the last component, which is separated by " and ", just like it would be written in English.

A more significant units of time will occur before than a least significant one. Therefore, 1 second and 1 year is not correct, but 1 year and 1 second is.

Different components have different unit of times. So there is not repeated units like in 5 seconds and 1 second.

A component will not appear at all if its value happens to be zero. Hence, 1 minute and 0 seconds is not valid, but it should be just 1 minute.

A unit of time must be used "as much as possible". It means that the function should not return 61 seconds, but 1 minute and 1 second instead. Formally, the duration specified by of a component must not be greater than any valid more significant unit of time.

Can somebody address the best way to go about solving this without all the dirty if else statements. I am considering looping through the array resolving the outputs but I am syntax new.

function formatDuration(s2) {
var arr=[],a=s2,y1=0,m1=0,d1=0,h1=0,m2=0,s1=0,
isYear=false,
isMonth=false,
isDay=false,
isHour=false,
isMinute=false,
isSecond=true;

if(s2>=31556926)isYear=true;
if(s2>=2629743.83)isMonth=true;
if(s2>=86400)isDay=true;
if(s2>=3600)isHour=true;
if(s2>=60)isMinute=true;    

    var yearConverter=function(s){
        limit=31556926;
        if(s>=limit) 
            a=a-limit; 
            y1=y1+1;
        if(s>=limit) 
            yearConverter(a);
        else 
            monthConverter(a);
    };

    var monthConverter=function(s){
        limit=2629743.83;
        if(s>=limit)
            a=a-limit;
            m1=m1+1;        
        if(s>=limit) 
            monthConverter(a);
        else
            dayConverter(a);
    };

    var dayConverter=function(s){
        limit=86400;
        if(s>=limit)
            a=a-limit; 
            d1=d1+1;
        if(s>=limit)
            dayConverter(a);
        else
            hourConverter(a);
    };      

    var hourConverter=function(s){
        limit=3600;
        if(s>=limit)
            a=a-limit; 
            h1=h1+1;
        if(s>=limit)
            hourConverter(a);
        else
            minuteConverter(a);
    };

    var minuteConverter=function(s){
        limit=60;
        if(s>=limit)
            a=a-limit; 
            m2=m2+1;
        if(s>=limit)
            minuteConverter(a);
        else 
            secondConverter(a);
    };  

    var secondConverter=function(s){
        s1=s;
        }

    if(isYear==true)
        yearConverter(a);   
        y1=y1-1;
        arr.push(y1);

    if(isMonth == true)
        monthConverter(a);
        m1=m1-1;
        if(m1<0)
            m1=0;
            isMonth = false;
        arr.push(m1);

    if(isDay==true)
        dayConverter(a);
        d1=d1-1;
        if(d1<0)
            d1=0;
            isDay = false;
        arr.push(d1);

    if(isHour==true)
        hourConverter(a);
        h1=h1-1;
        if(h1<0)
            h1=0;
        if(h1 == 0)
            isHour = false;
        arr.push(h1);

    if(isMinute==true)
        minuteConverter(a);
        m2=m2-1;
        if(m2<0)
            m2=0;
        if(m2 <= 0)
            isMinute = false;
        arr.push(m2);

    if(isSecond==true)
        secondConverter(a); 
        if(s1 == 60)
            s1 = 0;
        if(s1 <= 0)
            isSecond = false;
        arr.push(s1);
    console.log(arr);


    if(s2 < 1)
        return 'now';

    else if(isSecond == true && isMinute,isDay,isMonth,isYear == false && arr[5] == 1)
        return arr[5]+' second';

    else if(isSecond == true && isMinute,isDay,isMonth,isYear == false && arr[5] > 1)
        return arr[5]+' seconds';

    else if(isSecond,isMinute == true && isHour,isDay,isMonth,isYear == false && arr[4]==1 && arr[5]==1 )
        return arr[4]+' minute and '+arr[5]+' second';

    else if(isSecond,isMinute == true && isHour,isDay,isMonth,isYear == false && arr[4]==1 && arr[5]>1)
        return arr[4]+' minute and '+arr[5]+' seconds';

    else if(isSecond,isHour,isDay,isYear,isMonth == false && isMinute == true && arr[4]==1 )
        return arr[4]+' minute';

    else if(isHour,isDay,isMonth,isYear,isSecond == false && isMinute == true && arr[4]>1  )
        return arr[4]+' minutes';

    else if(isSecond,isMinute == true && isHour,isDay,isMonth,isYear == false && arr[4]==1 && arr[5]>1)
        return arr[4]+' minute and '+arr[5]+' seconds'; 

    else if(isMinute == true && isHour,isDay,isMonth,isYear == false && arr[4]==1 && arr[5]==1)
        return arr[4]+' minute and '+arr[5]+' second';

    else if(isSecond,isMinute == true && arr[4]>1)
        return arr[4]+' minutes and '+arr[5]+' seconds';

    else if(isSecond,isMinute,isHour == true && arr[3]==1)
        return arr[3]+' hour '+arr[4]+' minutes and '+arr[5]+' seconds';

    else if(isSecond,isMinute,isDay == true && arr[3]>1)
        return arr[3]+' hours '+arr[4]+' seconds and '+arr[5]+' seconds';

    else if(isMinute == false && isHour,isSecond == true && arr[3]>1)
        return arr[3]+' hours and '+arr[5]+' seconds';

    else if(isSecond,isDay,isMonth,isYear == false && isMinute,isHour == true && arr[3]>1)
        return arr[3]+' hours and '+arr[3]+' minutes';

    else if(isSecond,isMinute == false && isHour == true && arr[3]>1)
        return arr[3]+' hours';

    else if(isSecond,isMinute == false && isHour == true && arr[3]==0)
        return arr[3]+' hour';

};

Testing thread safety fails with Spock

The subject

I have some code that is decidedly not thread safe:

public class ExampleLoader
{
    private List<String> strings;

    protected List<String> loadStrings()
    {
        return Arrays.asList("Hello", "World", "Sup");
    }

    public List<String> getStrings()
    {
        if (strings == null)
        {
            strings = loadStrings();
        }

        return strings;
    }
}

Multiple threads accessing getStrings() simultaneously are expected to see strings as null, and thus loadStrings() (which is an expensive operation) is triggered multiple times.

The problem

I wanted to make the code thread safe, and as a good citizen of the world I wrote a failing Spock spec first:

def "getStrings is thread safe"() {
    given:
    def loader = Spy(ExampleLoader)
    def threads = (0..<10).collect { new Thread({ loader.getStrings() }}

    when:
    threads.each { it.start() }
    threads.each { it.join() }

    then:
    1 * loader.loadStrings()
}

The above code creates and starts 10 threads that each calls getStrings(). It then asserts that loadStrings() was called only once when all threads are done.

I expected this to fail. However, it consistently passes. What?

After a debugging session involving System.out.println and other boring things, I found that the threads are indeed asynchronous: their run() methods printed in a seemingly random order. However, the first thread to access getStrings() would always be the only thread to call loadStrings().

The weird part

Frustrated after quite some time spent debugging, I wrote the same test again with JUnit 4 and Mockito:

@Test
public void getStringsIsThreadSafe() throws Exception
{
    // given
    ExampleLoader loader = Mockito.spy(ExampleLoader.class);
    List<Thread> threads = IntStream.range(0, 10)
            .mapToObj(index -> new Thread(loader::getStrings))
            .collect(Collectors.toList());

    // when
    threads.forEach(Thread::start);
    threads.forEach(thread -> {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    // then
    Mockito.verify(loader, Mockito.times(1))
            .loadStrings();
}

This test consistently fails due to multiple calls to loadStrings(), as was expected.

The question

Why does the Spock test consistently pass, and how would I go about testing this with Spock?

How to test a http calls from a second class func call from within first class (APEX class testing/salesforce testing)

I have an apex class A. I'm calling the function of B class from within A.

class A{

B bobj=new B(); B.function2();

function1(); //within class A

}

This function1 and function2 are http calls to 2 diff rest services.

I wrote a test class with httpcallmockouts for the both function1 and function2. So the order goes like this inside APex Test class-

B objB=new B();

HttpResponse res = CalloutB.getInfoFromExternalService();

A objA=new A(); HttpResponse res = CalloutA.getInfoFromExternalService();

//Till this point my test runs successfully for http calls mock

Test.startTest();

objA.function1();

//Here I get an error http callout not supported for test methods for function2 of B class.

//If I change the order above to

//A objA=new A();

//HttpResponse res = CalloutA.getInfoFromExternalService();

//B objB=new B();

//HttpResponse res = CalloutB.getInfoFromExternalService();

//Then I get error http callout not supported for test methods for function1 of A class.

Test.stopTest();

So, how do you test the http call from within another's class function calls in the first class.

Jasmine html log doesnt work

My jasmine work good with cli but problem is display result in browser (ReferenceError: require is not defined). In my script i using require node function to load modules.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Jasmine Spec Runner v2.4.1</title>

  <link rel="shortcut icon" type="image/png" href="node_modules/jasmine-core/lib/jasmine-core/jasmine_favicon.png">
  <link rel="stylesheet" href="node_modules/jasmine-core/lib/jasmine-core/jasmine.css">

  <script src="/node_modules/systemjs/dist/system.js" type="text/javascript"></script>
  <script>  
    System.config({
        baseURL: '/app'
    });
      System.import('app.component.spec')
    .then(null, console.error.bind(console));
</script>

  <script src="node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
  <script src="node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
  <script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
  <script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>

  <!-- include source files here... -->
  <script src="server/scripts/auth.js"></script>

  <!-- include spec files here... -->
  <script src="spec/server/authSpec.js"></script>

</head>

<body>
</body>

</html>

Timeout on angular service test using $q and angular-extended-promises

I'm testing an angular service using angular extended promises as one of its dependencies. It looks like this:

angular.module('main')
    .service('MyService', ['_', '$q', 'DatabaseService', 
    function(_, $q, DatabaseService) {

      function loadResources(resources) {
          var resources = _.mapValues(resources, function(config, type) {
           return DatabaseService.getByType(type)
              .then(function(data) {
                  return index(type, data);
              });
          });
          return $q.props(resources);
      });

      var service = {
            loadResources: loadResources
      };

      return service;
    }
  ])
;

I want to make a test for the loadResources function and for this I stub DatabaseService.getByType function. I'm using mocha, chai, sinon running on karma. My test looks like this:

describe('[Service] MyService', function() {
    var MyService, DatabaseService, $q;
    var databaseBrand = [...]; // My fixtures

    beforeEach(function() {
        module('myApp');

        inject(function($injector) {
            MyService = $injector.get('MyService');
            DatabaseService = $injector.get('DatabaseService');
            $q = $injector.get('$q');

            sinon.stub(DatabaseService, 'getByType', function(type) {
                var typeResources = databaseBrand.filter(function(resource) {
                    return resource.type === type;
                });
                return $q.resolve(typeResources);
            });
        });
    });

    afterEach(function() {
        DatabaseService.getByType.restore();
    });

    it('loadResources method', function() {
        var configTest = { resources: [...] }; // input test data

        var promise = MyService.loadResources(configTest);
        return promise.should.be.fulfilled
            .then(function(brandResources) {
                console.log('PROMISE RESOLVED');
                expect(brandResources).to.be.an('object');
                // Other expects
            })
        ;
    });
});

When I run the test I have this timeout:

PhantomJS 2.1.1 (Mac OS X 0.0.0) [Service] MyService loadResources method FAILED
    timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

I have already seen some post when people suggest to use the .$apply() or $digest() of the rootScope to "force" the promise to be resolved. But the thing is that I'm a testing a service and I want to isolated it to test without any other wired behavior.

I have made modifications to recover the $rootScope during the beforeEach and to force the $digest within the afterEach and the log that I added in my test is shown (what is cool) but then I have some errors, attemping to request some resources that are not included in my scenario...

PhantomJS 2.1.1 (Mac OS X 0.0.0) [Service] MyService "after each" hook for "loadResources method" FAILED Unexpected request: GET /api/config No more request expected $httpBackend@bower_components/angular-mocks/angular-mocks.js:1211:90 sendReq@bower_components/angular/angular.js:10333:21 serverRequest@bower_components/angular/angular.js:10045:23 [native code] processQueue@bower_components/angular/angular.js:14567:30 bower_components/angular/angular.js:14583:39 $eval@bower_components/angular/angular.js:15846:28 $digest@bower_components/angular/angular.js:15657:36 $apply@bower_components/angular/angular.js:15951:31

Is there any way to avoid to use this $digest or $apply ? Why do I have to do this to allow $q.prop to resolve the promise if I'm within a service and not a controller ?

Thanks

Simple way to automate unit testing by logging an XML file and sending e-mail

I am new to the world of unit testing. I am currently setting up some unit+integration tests in the game engine Unity. I have a simple batch script that runs Unity via the command line and then outputs an XML file with the results (http://ift.tt/2cHIRFU).

Below is an example of a succesful test that is logged by saving an XML file on my local computer.

<?xml version="1.0" encoding="utf-8"?>
<!--This file represents the results of running a test suite-->
<test-results name="Unity Tests" total="3" errors="0" failures="0" not-run="0" inconclusive="0" ignored="0" skipped="0" invalid="0" date="2016-09-17" time="17:41:27">
  <environment nunit-version="2.6.2-Unity" clr-version="2.0.50727.1433" os-version="Microsoft Windows NT 10.0.14393.0" platform="Win32NT" cwd="C:\Users\UnitTesting_test" machine-name="Wikzo" user="Wikzo" user-domain="Wikzo" unity-version="5.4.0f3" unity-platform="StandaloneWindows" />
  <culture-info current-culture="en-US" current-uiculture="en-US" />
  <test-suite name="2_IntegrationTest" type="Assembly" executed="True" result="Success" success="True" time="4.060">
    <results>
      <test-case name="MoverTest" executed="True" result="Success" success="True" time="1.032">
        <reason>
          <message>
<![CDATA[Sent TestStarted
Pass 
]]>
          </message>
        </reason>
      </test-case>
      <test-case name="PowerUpTest" executed="True" result="Success" success="True" time="0.015">
        <reason>
          <message>
<![CDATA[Sent TestStarted
Pass 
]]>
          </message>
        </reason>
      </test-case>
      <test-case name="Sphere Drag Test" executed="True" result="Success" success="True" time="3.013">
        <reason>
          <message>
<![CDATA[Sent TestStarted
Pass (Plane)
]]>
          </message>
        </reason>
      </test-case>
    </results>
  </test-suite>
</test-results>

As I have never worked with XML nor automatic builds/testing before, I would like to get some pointers on how to approach this in a smart, yet simple, manner.

The plan right now is to run these tests via the command line in Windows every night on a local machine (maybe I will dive into servers and Jenkins in the future, but for now I am taking baby steps). Instead of manually having to read through the XML log, I would like to somehow get notified if the tests fail (result="Failure"). It would be nice if this could be done by e.g. sending me an e-mail or something similar that doesn't require too much setup.

How should I go about this? Is there an "IFTTT"-style of easy way to do this?

Thanks in advance.