dimanche 31 décembre 2017

Babel will not compile .test.js files while running Jest

While running yarn run jest --no-cache, An error is being thrown that says:

SyntaxError: Unexpected token import

My best guess is that babel is not reaching this this test file. Is their something special I need to include in .babelrc?

path:

/src/tests/LandingPage.test.js

test file:

import React from 'react';
import ReactShallowRenderer from 'react-test-renderer/shallow';
import LandingPage from '../../components/LandingPage';

test('Should render LandingPage correctly', () => {
  const renderer = new ReactShallowRenderer();
  renderer.render(<LandingPage />);
  expect(renderer.getRenderOutput()).toMatchSnapshot();
});

.babelrc :

{
  "presets": [
    "env",
    "react"
  ],
  "plugins": [
    "transform-class-properties",
    "transform-object-rest-spread"
  ]
}

Continuous Integration and Isolated Feature Testing

I've been given the task at work to move everyone from using TFS Source Control to Git as the Development Team has been lead to believe that Git may well be the silver bullet that will fix alot of the teams issues. I carried out the migration a month back and fortunately Git has fixed one thing for the team - code reviews are now alot more structured as pull requests in Git give the developer and reviewers a auditible platform to merge code into the master branch. There is however an issue of merge conflicts still, some of which taking up to 2 or 3 hours to resolve. The team are questioning if the tool (Git) is to blame whereas under analysis, I believe there are many other fundamental processes and pratices at fault within the team. To name but a few that don't sit well with me:

All products (Visual Studio Projects) maintained by the company sit under one Visual Studio Solution. This is around 40+ VS Projects ranging from Class Librarys, Services and Database tiers. If an update needs to be made to Production for one product, the whole Solution (along with the other products) needs to be released. There a 4 Scrum Teams working on the same VS Solution looking after their own Products. The Sprints all start on different days in a two-week cycle and therefore at any point in time, each team's Sprint is at a different state. Due to the issue raised in the first bullet point however, complexity ensues when it comes to the monthly release to Production as code for each product can be at separate stages. Anyway, that paints part of the scene to help pose my question. We're now using Git using the following structure:

Feature branch - Used for each User Story being worked upon in a Sprint Develop branch - All Feature branches are merged into here once the Pull Request has been approved and the change tested in isolation on a test server Master branch - Successfully tested features are cherry-picked into the Master branch My question is, how does DevOps / CI handle testing newly coded features in isolation? I've never worked in a place where we've tested new changes in total isolation therefore I can't get my head around why it's so important to my new Dev Team. In my opinion, the sooner we can test new changes with the rest of the codebase, the better.

Feel free to ask me any questions if you need me to elaborate on anything. Thanks in advance.

Execute multiple versions of a go program simultaneously from the command line

I have a go program that establishes a connection to and queries a Postgres database. I would like to test multiple processes accessing a database at the same time, similar to how it will be deployed and similar to how is done in this article:

Answer is very simple – it breaks when I'll run it many times in parallel. How? Let's see:

psql -c 'truncate test'; for i in {1..10}; do ./test.pl & done; sleep 5; killall perl`

I've read through the documentation on psql -c but I'm still unclear as to how the command works. I'm unsure what language that accepts. My guess is perl, judging by the killall command and my very basic understanding of the language.

How could one accomplish this for a go program?

Invalidate node cache when using Jest

I have a file with object that gets populated with process.env properties:

env.js

console.log('LOADING env.js');

const {
  PROXY_PREFIX = '/api/',
  USE_PROXY = 'true',
  APP_PORT = '8080',
  API_URL = 'http://ift.tt/2zURGru',
  NODE_ENV = 'production',
} = process.env;

const ENV = {
  PROXY_PREFIX,
  USE_PROXY,
  APP_PORT,
  API_URL,
  NODE_ENV,
};

module.exports.ENV = ENV;

Now I try to test this file with different process.env properties:

env.test.js

const envFilePath = '../../config/env';

describe('environmental variables', () => {
  const OLD_ENV = process.env;

  beforeEach(() => {
    process.env = { ...OLD_ENV };
    delete process.env.NODE_ENV;
  });

  afterEach(() => {
    process.env = OLD_ENV;
  });

  test('have default values', () => {
    const { ENV } = require(envFilePath);
    expect(ENV).toMatchSnapshot();
  });

  test('are string values (to avoid casting errors)', () => {
    const { ENV } = require(envFilePath);
    Object.values(ENV).forEach(val => expect(typeof val).toEqual('string'));
  });

  test('will receive process.env variables', () => {
    process.env.NODE_ENV = 'dev';
    process.env.PROXY_PREFIX = '/new-prefix/';
    process.env.API_URL = 'https://new-api.com/';
    process.env.APP_PORT = '7080';
    process.env.USE_PROXY = 'false';

    const { ENV } = require(envFilePath);

    expect(ENV.NODE_ENV).toEqual('dev');
    expect(ENV.PROXY_PREFIX).toEqual('/new-prefix/');
    expect(ENV.API_URL).toEqual('https://new-api.com/');
    expect(ENV.APP_PORT).toEqual('7080');
    expect(ENV.USE_PROXY).toEqual('false');
  });
});

Unfortunately, even though I try to load the file in every test separately the file gets loaded only once, making the third test fail with:

Expected value to equal:
  "dev"
Received:
  "production"

I also know that because console.log('LOADING env.js'); gets fired only once.

I tried to invalidate Nodes cache like:

  beforeEach(() => {
    delete require.cache[require.resolve(envFilePath)];
    process.env = { ...OLD_ENV };
    delete process.env.NODE_ENV;
  });

but require.cache is empty {} before each test so it seems that Jest is somehow responsible for importing the file.

I also tried to run yarn test --no-cache but didn't help.

So what I want is to load env.js before each test so I can test how it behaves with different node environmental variables.

Modifying Django settings in tests

From Django docs:

You shouldn’t alter settings in your applications at runtime. For example, don’t do this in a view:

from django.conf import settings

settings.DEBUG = True   # Don't do this!

The only place you should assign to settings is in a settings file.

I've noticed that Django testing code does alter settings. Why is it ok to do it there?

when using jmockit, how to batch mock classes by special class and do inverse

In the spring environment using jmockit, I usually want to test a class that needs to mock many other many classes (which this class dependencies).

E.g: There are now Class1, Class2, ,, Class20.

Class1 depends on Class2, Class3 ,,, Class20 (via spring ioc).

I want to test Class1, need mock Class2, Class3 ,,, Class20 all, it is to much trouble.

How to write only once code can mock Class2, Class3 ,,, Class20.

The function I expect is this:

@Mocked (excludeClasses = {Class1}) (excludeClasses expect is a variable paramter)

@Test

public void methodOfClass1 () {

}

Integration testing with spark server

Hi im trying to IT my spark server. My intentions are to test all the controller functions. I have thought about few options: 1. Set up a server that will start when running the tests, and terminate when the tests are over.

The problem with this solution is that I have to rewrite my whole server logic to the new server (we start server from scratch every time we set the server before the testing).

  1. Initiate a controller from the test class (essential to initiate and not static call, in order to configurate the right db to the controller) that will call the controller functions and check their answers.

This is my favorite one, but it means that I have to mock a spark request. Im trying to build a spark request, and spark response objects, to send to my controller, and hanv't found a single way to do that properly (and how to send paramters, set url routes etc..)

@Test
 Public void testTry(){
   String expectedName = "mark";
   myController myCtl = new myController()
   Request req = null;
   Response res = null;

   String childName =      myCtl.getChildNameFromDB(req, res);

  assertEquals(childName, expectedName);
}

  1. The last one is to do the exact logic of the controler function in the test, and instead of getting the parameters from the request, ill initiate them myself. For example, instead of: String username = req.params(""usrName") It will be: Strimg username = "mark"

But that solution will demand copying a lot of code, and you might miss a little code line which might make the test succeed when in reality, the controller function fails (or doesnt deliver as wanted).

What do you think about Integratiom testing a spark driven server ? Im open minded to new solutions aswell, thanks!

python tests not deployed

I wrote a test that inherits from a built-in test, but it fails on my build server. When comparing the dev environment with the build server, and I get the following difference:

Dev environment (mac):

>>> len(os.listdir(os.path.dirname(test.__file__)))
1418

Build server (linux):

>>> len(os.listdir(os.path.dirname(test.__file__)))
8

Basically, when installing Python, it didn't deploy its test files. How do I fix this?

Thanks!

include external jar dependencies spring boot test

I have spring boot applications which shares the same entities layer, until now the entities were duplicated among all the projects and I had test on each on the modules which worked perfectly. I extracted all the entities into a separated maven artifact and I have added dependencies from my projects to the new artifact. Everything seems to work fine except for my tests which are not able to run. I get the following error when running my tests:

Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: PIM_SECURITIES
at org.hsqldb.error.Error.error(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.error.Error.error(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.SchemaManager.getTable(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.ParserDQL.readTableName(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.ParserDQL.readSimpleRangeVariable(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.ParserDML.compileInsertStatement(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.ParserCommand.compilePart(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.ParserCommand.compileStatements(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.Session.executeDirectStatement(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.Session.execute(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]
at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source) ~[hsqldb-2.2.8.jar:2.2.8]

below is the definition of my spring boot test class

@ContextConfiguration(classes = {AccountsDao.class, SecuritiesDao.class,  TasksDao.class})
@RunWith(SpringRunner.class)
@DataJpaTest
@Transactional
@ActiveProfiles("test")
public class DalLayerTests extends 
AbstractTransactionalJUnit4SpringContextTests {}

the object not found is in the entities artifact.

I have tried adding the artifact to run with the test scope in maven, but it didn't help. I have tried to add it to the annotation @ContextConfiguration(classes) but it didn't help as well.

Your help will appreciated.

samedi 30 décembre 2017

svm error test data does not match model?

I'm trying to train an svm classifier to do prediction. When I try to use the trained model, I get this error: test data does not match model. I am not why this is happening. This is my code

# to prepare the training and testing data
dat = data.frame(x = rbind(tmp1, tmp2), y = as.factor(c(rep(1, 300), rep(-1, 300))))
set.seed(1)
train_ind = sample(seq_len(nrow(dat)), size = 500)
train = dat[train_ind, ]
test = dat[-train_ind, ]

# training and prediction
library('e1071')
svmfit = svm(y ~ ., data = train, kernel ='linear', cost = 10, scale = FALSE)
ypred = predict(svmfit, test)
table(predict=ypred, truth = test$y)

issue with test code +rating bar code

how can i code : rating bar + test*

*test :-if user click less than 4 star it will show a toast messg say thank you . - and if user click more than 4 star it will send him to my app to review. Thank you.

spring boot Dao test

i have a test case for dao implementation.
Test Class Code -

@RunWith(SpringRunner.class)
@RestClientTest({XyzDaoImpl.class})
@TestPropertySource(locations = "classpath:application-test.properties")
public class XyzDaoTest {

    @Autowired
    XyzDaoImpl xyzDaoImpl;

    @Test
    public void testGetXyzDetails(){
        assertThat(xyzDaoImpl.getXyzDetails("123", null)).isNotNull();
    }
}

xyzDaoImpl.getXyzDetails method implementation calls a backend using RestTemplate.
This test works fine when my config class code contains -

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

but if i create the rest template using builder to set timeout etc , Test fails -

@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder
            .setConnectTimeout(timeout)
            .build();
}

Tried creating Bean using @Profile("test") default and @Profile("!test") - custom setting, still test fails.
Error is -

 testException = java.lang.AssertionError: No further requests expected: HTTP POST http://... url.

How to do black and white box testings of this part of code?

public class DailyMovementsRecords extends javax.swing.JFrame {

Connection conn; 
Statement stmt; 
PreparedStatement pst;
public void reloaded() {
           try {
           stmt = CreateDB.getConnection().createStatement();
    } catch (Exception excp) {
        JOptionPane.showMessageDialog(null, "Error on database connection", "Statement error", JOptionPane.ERROR_MESSAGE);
    }//try catch closed

    try {
     String sql = ("SELECT * FROM movements_data ORDER BY No");
     int Numrow=0;

        ResultSet result = stmt.executeQuery(sql);
        while (result.next()) {

            if (run==1){
                 int key =0;
     DefaultTableModel dtm = (DefaultTableModel) tableRecords.getModel();
     key = tableRecords.getRowCount()+1;
     dtm.setRowCount(key);  

            }

            tableRecords.setValueAt(result.getString(1).trim(), Numrow, 0);
            tableRecords.setValueAt(result.getString(2).trim(), Numrow, 1);
            tableRecords.setValueAt(result.getString(3).trim(), Numrow, 2);
            tableRecords.setValueAt(result.getString(4).trim(), Numrow, 3);
            tableRecords.setValueAt(result.getString(5).trim(), Numrow, 4);

   Numrow++;

        }//while closed
       run =0;
    } catch (SQLException sqlex) {
        JOptionPane.showMessageDialog(null, "Error on retrieving values", "Error", JOptionPane.ERROR_MESSAGE);
    }//try catch closed
}//reloaded() closed

I've been asked to apply white box and black box testing techniques on this part of code. Is it possible to do it, without having other classes?

Jest with special tests run on occasion

How do I write Jest tests that only runs when specifically invoked on the command line?

I want to have integration-like tests that interact with online services from Google and Amazon in a React project.


If I create a differently named test file src/google.itest.js:

  • Good: It is not normally run by jest
  • Good: It resides where all other tests are
  • Bad: jest cannot be made to run it:

jest --testPathPattern="\.itest"
Jest still does not run the tests, probably because it is blocked by the testMatch configuration option: testMatch:

**/__tests__/**/*.js?(x),**/?(*.)(spec|test).js?(x)

How do I write Jest tests that only runs when specifically invoked on the command line?

Testing Xamarin Navigation methods with context Binding on destination page fails

I have a problem with Xamarin framework. I am trying to test a Navigation.PushAsync method and I get an error:

"You must call Xamarin.Forms Init() prior using it"

Scenario

Just imagine a simple content page in Xamarin which looks like this in the code behind.

public partial class TesterPage : ContentPage
{


    public TesterPage()
    {
      InitializeComponent();
    }
}

And here is the XAML part for it:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage 

         xmlns="http://ift.tt/1i1Py1I"
         xmlns:x="http://ift.tt/Ten7b2"
         x:Class="BoatInspectorPMS.TesterPage">
<ContentPage.Content>
    <StackLayout>
        <Label Text="Welcome to Xamarin Forms!" />
    </StackLayout>
</ContentPage.Content>
</ContentPage>

This is out destination page. We have the origin page that looks like this partly.

public class MainViewModel
{
     private readonly IPageService _pageService;

     public MainViewModel(IPageService pageService)
     {
        _pageService = pageService;
     }

     public async Task NewSurvey()
     {
        await _pageService.PushAsync(new TesterPage());
     }
}

The interface IPageService looks like this:

public interface IPageService
{
    Task PushAsync(Page page);
}

So we want to run a test which looks like this. Here is our test.

    [Test]
    public async Task OurTest()
    {           
        //mock PageService
        var pageService = new Mock<PageService>();
        var mvm = new MainViewModel(pageService.Object);

        await mvm.NewSurvey();
        pageService.Verify(p => p.PushAsync(It.IsAny<TesterPage>()));

    }

I get an error in the constructor of TesterPage at InitializeComponent() at the moment when it enters auto generated code

  private void InitializeComponent() {
        global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(TesterPage));
    }

Pretty stuck on this issue. Hope someone has come across a similar situation. Thank you.

test process.env with Jest

I have an app that depends on environmental variables like:

const APP_PORT = process.env.APP_PORT || 8080;

and I would like to test that for example:

  • APP_PORT can be set by node env variable.
  • or that an express app is running on the port set with process.env.APP_PORT

How can I achieve this with Jest? Can I set these process.env variables before each test or should I mock it somehow maybe?

How to test redux saga with jest?

Just new in react , react-redux/saga and jest

consider:

-----The Componnent ()----

componentDidMount() {

    this.props.actions.initTodos(
        axios,
        ajaxURLConstants.WP_GET_TODOS,
        appStateActions.setAppInIdle,
        appStateActions.setAppInProcessing,
        todosActions.todosInitialized
    );

}

So when my TodoApp component did mount, it will dispatch the INIT_TODOS action which then my root saga is listening , and when it caught it, will spawn the appropriate worker saga to act accordingly.

-----The Corresponding Worker Saga-----

export function* initTodosSaga( action ) {

    try {

        yield put( action.setAppInProcessing() );

        let response = yield call( action.axios.get , action.WP_GET_TODOS );

        if ( response.data.status === "success" )
            yield put( action.todosInitialized( response.data.todos ) );
        else {

            console.log( response );
            alert( response.data.error_msg );

        }

    } catch ( error ) {

        console.log( "error" , error );
        alert( "Failed to load initial data" );            

    }

    yield put( action.setAppInIdle() );

}

-----The Test So Far-----

import todos             from "../../__fixtures__/todos";
import { initTodosSaga } from "../todosSaga";

test( "saga test" , () => {

    let response = {
            status : "success",
            todos
        },
        action = {
            axios : {
                get : function() {

                    return new Promise( ( resolve , reject ) => {

                        resolve( response );

                    } );

                }
            },
            WP_GET_TODOS       : "dummy url",
            setAppInIdle       : jest.fn(),
            setAppInProcessing : jest.fn(),
            todosInitialized   : jest.fn()
        };

    let initTodosSagaGen = initTodosSaga( action );

    initTodosSagaGen.next();

    expect( action.setAppInIdle ).toHaveBeenCalled();

} );

-----The Test Result So Far----- enter image description here

So the important part is this

console.error node_modules\redux-saga\lib\internal\utils.js:240

uncaught at check put(action): argument action is undefined

but I have console.log the action i passed on my test inside the worker saga and indeed it is not undefined

what am I missing?

Thanks in advance.

vendredi 29 décembre 2017

Run db action in yesod test

In my yesod test I want to be able to modify a record in the db in the middle of the test.

Here is the code I came up with

        yit "post is created by authorized user" $ do
            request $ do
                addPostParam "ident" "dummy"
                setMethod "POST"
                setUrl ("http://localhost:3000/auth/page/dummy" :: Text)
            update 0 [UserAuthorized =. True]
            postBody PostR (encode $ object [
                "body" .= ("test post" :: Text),
                "title" .= ("test post" :: Text),
                "coverImage" .= ("test post" :: Text),
                "author" .= (0 :: Int)
                ])
            statusIs 200

This fails with the error

• Couldn't match expected type ‘IO a0’
              with actual type ‘ReaderT backend0 m0 ()’
• In the second argument of ‘($)’, namely
    ‘update 0 [UserAuthorized =. True]’

  In a stmt of a 'do' block:
    runIO $ update 0 [UserAuthorized =. True]
  In the expression:
    do { settings <- runIO
                     $ loadYamlSettings
                         ["config/test-settings.yml", "config/settings.yml"] [] useEnv;
         foundation <- runIO $ makeFoundation settings;
         yesodSpec foundation $ do { ydescribe "Auth" $ do { ... } };
         runIO $ update 0 [UserAuthorized =. True];
         .... }

I can tell this is because update returns m () instead of YesodExample site () like request, postBody and statusIs do.

How would I be able to do a db update inside of this test?

How to write inputs for American Fuzzy Lop?

I am trying to use American Fuzzy Lop, so far I got everything installed and trying to fuzz "as an example for a popular program" the program Putty-gen.

However, I'm having a problem in determining the test cases, and the difference of files between a program that reads input from user on run time, and a program that reads arguments.

Can someone please explain in short the difference between the above? and give an example on how to write a simple test case for the program putty-gen or similar?

I am testing the program on Ubuntu CLI, not GUI.

Thank you.

Tests naming convention for unexported functions in Go

I can't trace where I know it from, but normally if one writes a test for method Foo, the corresponding test is named TestFoo.

If one tests an unexported function, say foo, what the name of the test should be then?

My question comes from the fact, that JetBrains IDE for Go, when asked to generate a test for an unexported function, generates something like Test_foo.

This behavior may have sense, because if you have Foo and it's unexported counterpat foo in the same package, you'd want to distinct tests for them somehow (at least for jump to test feature in IDE).

So is there any convention on naming tests after unexported functions?

BTW: documentation for the Go testing package says, that a test is executed if it is:

any function of the form

func TestXxx(*testing.T)

where Xxx can be any alphanumeric string (but the first letter must not be in [a-z]) and serves to identify the test routine.

Which means, that any test having underscore in its name shouldn't be executed by go test. However, we all know, that such tests work just fine.

Rails, can validate a user crating a record is admin, from the model?

I am attempting to make a new record object invalid if the user_id of the object is associated with an account that is not admin.

In the model I'd like to make a validation checks if the object to be created user_id.admin == true.

Neither of these solutions work:

  validates :user_id, User.find(:user_id).admin?

  before_save :user_is_admin, User.find(self.user_id).admin?

So, my question is, how do I write a validation that looks up the user and checks if they are an admin, and throws an error if they are not?

P.S. I am already doing admin checking in the controller as a before_action, but I'd like to invalidate the object if a non admin user manages to create one somehow...and for testing purposes.

If this isn't a best practice I'd still like to know a bit more about creating validity checks in rails.

jeudi 28 décembre 2017

How do I get liquibase to skip table creation if it already exists with liquibase formatted sql?

This is what I have

--preconditions onFail:CONTINUE
--preconditions not tableExists tableName:QRTZ_CALENDARS schemaName:dbo
CREATE TABLE dbo.QRTZ_CALENDARS (
 SCHED_NAME VARCHAR (120)  NOT NULL ,
 CALENDAR_NAME VARCHAR (200)  NOT NULL ,
 CALENDAR IMAGE NOT NULL
) 
GO

Background. I'm using liquibase to setup a h2 database for test cases in java.

Test & Target not working with AMP or Facebook

I am running a Facebook ad campaign that links to a page that’s running an A/B test with adobe. If you go to the page via your mobile phone it works just fine, but if you click on it in Facebook the Facebook mobile browser strips ensigbten & adobe code. Is there a reason and/or work around for this?

What is the best Unit Test framework for an AAR project?

I am building an android custom library (AAR).
What is the best unit test framework for a project, with less UI and more to do with dependency testing and integration testing?

Using assert with fixed sized arrays and printing them in Rust

I have written some tests, where at the end I need to assert that two arrays are equal. In some tests arrays have size and type of [u8; 48], whereas in others [u8; 188]. So all of them are u8 (byte) arrays. For example, one test:

#[test]
fn mul() {
    let mut t1: [u8; 48] = [248, 132, 131, 130, 138, 113, 205, 237, 20, 122, 66, 212, 191, 53, 59, 115, 56, 207, 215, 148, 207, 41, 130, 248, 214, 42, 124, 12, 153, 108, 197, 99, 199, 34, 66, 143, 126, 168, 88, 184, 245, 234, 37, 181, 198, 201, 84, 2];
    let t2: [u8; 48] = [232, 142, 138, 135, 159, 84, 104, 201, 62, 110, 199, 124, 63, 161, 177, 89, 169, 109, 135, 190, 110, 125, 134, 233, 132, 128, 116, 37, 203, 69, 80, 43, 86, 104, 198, 173, 123, 249, 9, 41, 225, 192, 113, 31, 84, 93, 254, 6];

    // some computation goes here.

    assert_eq!(t1, t2, "\nExpected\n{:?}\nfound\n{:?}", t2, t1);
}

But, I get multiple errors here, for one:

[u8; 48] cannot be formatted using :?

Trying to print them here as slices also like t2[..] or t1[..] doesn't seem to work. Another error is this:

binary operation == cannot be applied to type [u8; 48]

Any ideas how to use assert with these arrays and print them?

Testing an AJAX call in phpunit / symfony, using client or crawler

i want to test a conroller which generates a page with a field that changes dynamicly with ajax.

Here is the code of ajax :

<script>
  var $groupeCompetence = $('#requete_prestataire_groupeCompetence');
// When sport gets selected ...
$groupeCompetence.change(function() {
  // ... retrieve the corresponding form.
  var $form = $(this).closest('form');
  // Simulate form data, but only include the selected sport value.
  var data = {};
  data[$groupeCompetence.attr('name')] = $groupeCompetence.val();
  // Submit data via AJAX to the form's action path.
  $.ajax({
    url : $form.attr('action'),
    type: $form.attr('method'),
    data : data,
    success: function(html) {
      // Replace current position field ...
      $('#requete_prestataire_competence').replaceWith(
        // ... with the returned one from the AJAX response.
        $(html).find('#requete_prestataire_competence')
        );
      // Position field now displays the appropriate positions.
    }
  });
});
</script>

How can i call this code from phpunit using client or crawler ?

I tried :

$this->client->request(
                'POST',
                '/',
                array('requete_prestataire[groupeCompetence]' =>2),
                array(),
                array(),
                array('HTTP_X-Requested-With' => 'XMLHttpRequest',
                    ));

But it doesnt work.

Thanks a lot !

Angular async detect changes

How can I "detect changes" in testing Angular without testbed?

With a component, I will have this:

it('should work', async(() => {
  const fixture = TestBed.createComponent(TestComponent);
  // do some async call
  fixture.detectChanges();   // <=== This is what I want
  expect(something).toEqual(somethingElse);
});

With a service, I don't always have a testbed. How to tell angular to wait before asserting? Example:

it('should work', async(() => {
  const service = new MyService();
  const sub = service.emitter$.subscribe((val) => {
    // expect(val).toEqual(otherVal);
  });
  service.doAsyncWork();
});

How to get these connected? What if I have two phases to check (e.g. once before that async work, once after, but all after some initial period)?

how to use puppeteer mouse.click

I use puppeteer for testing UI.

I collect the coordinate then use mouse.click to simulate click event. But invalid!

I wrong ?

const puppeteer = require('puppeteer')

;(async () => {

  const browser = await puppeteer.launch({
    headless: false,
    slowMo: 20
  })

  const page = await browser.newPage()

  await page.goto('http://ift.tt/2C5tlVO')

  await page.waitFor(5000)

  await page.setViewport({
    width: 1400,
    height: 800
  })

  const m = page.mouse

  await m.click(50, 50)  // coordinate

  await page.waitFor(5000)

  await page.screenshot({path: 'test.png'});
  await browser.close();
})()

Running async tests for View Model in Xamarin and executing commands

This is a bit tricky to explain but hopefully my question will make sense. I have a long run of asyn methods that I want to test from my nUnit test project. There are twi scenarions the first one runs smooth and the second one fails but I want to fix the second one because it is correct.

Scenario N1 - tests green

[Test]
public async  Task NameNameName()
{
    var pageService = new Mock<IPageService>();
    var mvm = new MainViewModel(pageService.Object);
    await mvm.NewSurvey();

   Assert... bla bla all good
}

This test addresses a method called NewSurvey() in the MainViewModel class of my project which looks like this.

    public async Task NewSurvey()
    {

        var surveyController = ServiceLocator.Current.GetInstance<SurveyController>();
        var response = await surveyController.PostSurvey(CreateNewSurveyResourceObject());
        SetSurveyContext(response);
    }

As you might imagine when we hit PostSurvey we go along a continuous way of async await methods and when we get to the last one magic happens we come back to continue inside the method where we started from ie. execute SetSurveyContext(response);

Now, I made this method public just to see if it passes the test. I want to set it private since in the real app scenario the method is called through ICommand interface which is set up as follows in the constructor.

 NewSurveyCommand = new Command(async () => await NewSurvey());

With an appropriate public field

 public ICommand NewSurveyCommand { get; private set; }

Which is referenced from Xamarin xaml. The logic works fine in the app but I also want to write the test for it so here is how I do it.

[Test]
public async  Task NameNameName()
{
    var pageService = new Mock<IPageService>();
    var mvm = new MainViewModel(pageService.Object);

    //this time
    await Task.Run(() => mvm.NewSurveyCommand.Execute(null));
    //or below doesn't matter works the same way
    //mvm.NewSurveyCommand.Execute(null);

   Assert... bla bla all BAD this time
}

So the problem is when we get to the end of the chain of await async methods we get thrown back into the test method instead of finishing up the method inside MainViewModel where SetSurveyContext(response); actually sets what we are supposed to check for in the tests and the tests fail.

I have no idea how to fix this. Hopefully I have explained the issue well enough to someone to understand and possibly help me if they have been across the same problem. Thanks.

Codeception cleanup vs. depends

When working with Codeception Acceptance tests i got to realise the best way is to cleanup the database before every test and make every test independent.

But some Cest Tests depend on each other. So if i write:

/**
 * @depends createObjectBase
 * @___skip     
 */   
 public function createObjectMore(AcceptanceTester $I)
 {

the data created in the DB from the createObjectBase test is gone because of the cleanup. But that data is needed for the createObjectMore test.

I cannot combine them into one test because in reality there are multiple areas with very different tests, so createObjectMore is just a placeholder here.

So whats the best way to handle this?

Using logical or in seeInDatabase

How can i implement a logic 'or' operator in Codeception's seeInDatabase method?.

For example: the methods syntax is

seeInDatabase('table', array('column1' => 'value1', 'column2' => 'value2'));

Wich generates this query

SELECT COUNT(*) FROM `table` WHERE `column1` = 'value1' AND `column2` = 'value2'

How can i generate the following query?

SELECT COUNT(*) FROM `table` WHERE `column1` = 'value1' AND (`column2` = 'value2' OR `column2` = 'value3')

Thanks for your help!

Jest mock function's constants doesnt work

i have little experience with jest as i am trying to change variable in my function as we expect to have error thrown if the function's inner variable(baseUrl) changed to null

my function :

buildUrl.js

  export function buildUrl(contentId, data, options = {}) {
  let baseUrl = config.has('imgBaseUrl') && config.get('imgBaseUrl');
  if (!baseUrl) {
    throw new Error('some error');
  }
...

i need to mock the baseUrl to value of null for example and test it

buildUrl.test.js

import {buildUrl} from "./buildURL";
....
 it('throw an error when "baseUrl" is not configured', () => {

   let mockBaseUrl = {baseUrl: null};
   jest.mock('./buildURL', ()=> mockBaseUrl);
   // jest.mock('../../../config/test', ()=>mockImgBaseUrl); // or mock the config to be used by the function?

   expect(()=> buildUrl('1.44444', data[0], defaultOptions)).toThrow(
     'some error'
   );
   });

another approach using jest.fn() didnt work as expected , maybe i am missing something here...

Return data null when unit test the service using Moq

I am having a problem when using the Moq for unit testing the a function which accepts number of parameters. I did the bellow steps to moq the service.

  1. Created a mock object to interface. the relevant method in the interface contains four arguments namely int type, a collection and a object. so i initailized the variable needed for those first,

  2. Then setup the mock object to return a a predefined type of object.

  3. After that the relevant method in the service class is called with the reuired arguments but the method deos not return the object that it is supposed to return like above it rather sends a object with null values.

Am I missing anything in the code bellow?

Collection spec = new Collection() { new MyIdSample() { SampleID = 1234 } }; int index = 0; int maxNoOfRows = 2; MyDocumentListSortFields sortFeild = new MyDocumentListSortFields() { Descending = false, SortField = MyDocumentListSortFields.SortFields.Date };

var bundleOfObjects = new bundleOfObjects { Entry = new List() };

MySampleDocument resource_1 = new MySampleDocument(); resource_1.Id = "1005823"; resource_1.Description = "Test 1"; resource_1.Created = "11/20/2017 12:59:47 PM";

bundleOfObjects.AddTobundleOfObjects(resource_1, null); var m_documentWrapperHelperMock = new Mock(); var m_configMock = new Mock();

m_documentWrapperHelperMock.Setup(x => x.GetSampleDocumentsWithOffSets(spec, index, maxNoOfRows, sortFeild)).Returns(bundleOfObjects);

var service = new MySampleDocumentService(m_configMock.Object, m_documentWrapperHelperMock.Object);

Testing a deep buffered video? How to Automate?

I would very much like to know anyone's thoughts on how to test a video that has been deep buffered. In simple terms, the video buffers ahead of the normal (shallow buffer) when the network conditions are stable. Then in the event of it being degraded, the end-user can still stream the video for a period of time uninterrupted.

I am particularly interested in automated test scenarios.

Thank you!

Ubuntu terminal commands using SCSI tool induce disk failure

I have written a code to do read & write(random file) pulling a hard disk performance.But,I also want to check when there is a disk failure.So,I am trying to induce disk failure using SCSI tool.But,I am unable to get any insights for it.Can anybody direct me to do the same.

how can I write a test case which is valid and also invalid

How can i write a test-case which is a valid test-case and also a invalid test-case ? i have tried many scenarios like user login , data saved in cache memory but not got the exact answer please help

What type of testing can be performed on content and data driven websites?

Can anyone tell me what type of testing can be performed on content and data-driven websites?

JavaScript RegExp test returns wrong value

I am solving curious problem right now. I am testing a string with regexp and it returns false eventhough it should return true. I am implementing it in javascript. I have this function

function isPhoneNumberValid(phoneNumber) {
  return /^\+\d{12}$/.test(phoneNumber);
}

phoneNumber is a variable in format of + and 12 numbers after (+421123123123 for example). I've played around with different versions of regexp like /^\+[0-9]{12}$/.

According to sites like http://ift.tt/2AnY9QE my regexp should be working for the format I want, yet it returns false still. When I tried testing this regexp /^\+[0-9]/ it returned true when only +3 was written, I guess the problem is with the numbers count?

Parameter phoneNumber received in the function is correct one so I don't think the mistake is there. Also no combination of modifiers helped.

Here is a log of this function

function isPhoneNumberValid(phoneNumber) {
    console.log('ph:'+phoneNumber);
    console.log(/^\+\d{12}$/.test(phoneNumber));
}

enter image description here

mercredi 27 décembre 2017

How to use string functions in CBTA

I have a string "Credit MB warranty PT01210636 has been saved". How to fetch "only number" from this string in CBTA 7.2. What will be the split formula? My Try- I have stored the above string in "COMPLETE_TEXT" and I am using below split formula- %=Split($COMPLETE_TEXT$,”“)(3)%

But it is not working. Any help would be appreciated

Getting class information OTF while running test automation

Has anyone tried to gather information of which part of code is being executed while running test automation using Selenium or similar tools using EMMA etc?

Ansible uri call with Django JWT token

I would like to call django server with ansible:

I have called:

- name: Check status 200
    uri:
      url: https:///api/users/api-token-auth/
      method: POST
      headers:
        Content-Type: "application/json"
      body: '{"username": "username", "password": "password"}'
      return_content: yes

    register: token

and I get the token. Now I would like to use this token for the next call, but I can't figure out how this is working....

I try

- name: Check that LOGIN returns a status 200
  uri:
    url: https:///api/users/auth/
    method: POST
    headers:
      Content-Type: "application/json"
      Authorization: "JWT "
    body: '{"username": "user", "password": "pass"}'
    return_content: yes

  register: webpage

but I get error:

 "msg": "The task includes an option with an undefined variable. The error was: ansible.utils.unsafe_proxy.AnsibleUnsafeText object has no element {u'cookies': {}, u'vary': u'Accept', u'access_control_allow_headers': u'Access-Control-Allow-Origin, Content-Type, X-CSRFToken, Authorization, Access-Bw, Content-Disposition', u'access_control_allow_methods': u'GET, DELETE, POST, PUT, OPTIONS', u'access_control_allow_credentials': u'true', u'content': u'{\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hcmtvLnphZHJhdmVjQHJlc3VsdC5zaSIsImV4cCI6MTUxNTAxNDE1OSwidXNlcl9pZCI6NCwidXNlcm5hbWUiOiJtYXJrby56YWRyYXZlY0ByZXN1bHQuc2kifQ.otlXbiuXnDJPiLrEKdMTKBgBMbvIGApBVH_aPI5mSd4\"}', 'failed': False, u'json': {u'token': u'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im1hcmtvLnphZHJhdmVjQHJlc3VsdC5zaSIsImV4cCI6MTUxNTAxNDE1OSwidXNlcl9pZCI6NCwidXNlcm5hbWUiOiJtYXJrby56YWRyYXZlY0ByZXN1bHQuc2kifQ.otlXbiuXnDJPiLrEKdMTKBgBMbvIGApBVH_aPI5mSd4'},....

What is the right way to do it?

Class WebTestCase not found when checking debug:wiring

When checking php bin/console debug:wiring, I get the following errors:

In FileLoader.php line 168:

  Class Symfony\Bundle\FrameworkBundle\Test\WebTestCase not found in /vagrant/mysymfony/app/config/services.yml (whic
  h is being imported from "/vagrant/mysymfony/app/config/config.yml").


In WebTestCase.php line 17:

  Class Symfony\Bundle\FrameworkBundle\Test\WebTestCase not found


In WebTestCase.php line 21:

  Class Symfony\Bundle\FrameworkBundle\Test\KernelTestCase not found


In KernelTestCase.php line 24:

  Class PHPUnit\Framework\TestCase not found

The error is due to the following file:

<?php
/**
 * This file is part of the RestExtraBundle package [1].
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this[1] source code.
 *
 * @license    MIT License
 * [1] http://ift.tt/2E2p6HC
 */
namespace AppBundle\Test;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;

/**
 * @author William Durand <william.durand1@gmail.com>
 */
abstract class WebTestCase extends BaseWebTestCase
{
    protected function assertJsonResponse($response, $statusCode = 200)
    {
        $this->assertEquals(
            $statusCode, $response->getStatusCode(),
            $response->getContent()
        );
        $this->assertTrue(
            $response->headers->contains('Content-Type', 'application/json'),
            $response->headers
        );
    }

    protected function jsonRequest($verb, $endpoint, array $data = array())
    {
        $data = empty($data) ? null : json_encode($data);
        return $this->client->request($verb, $endpoint,
            array(),
            array(),
            array(
                'HTTP_ACCEPT'  => 'application/json',
                'CONTENT_TYPE' => 'application/json'
            ),
            $data
        );
    }
}

The file is in the following directory structure:

.
├── AppBundle.php
├── Controller
│   ├── DefaultController.php
│   └── FooController.php
└── Test
    └── WebTestCase.php

And that WebTestCase class is used in the following file:

<?php

namespace Tests\AppBundle\Controller;

use AppBundle\Test\WebTestCase;

class FooControllerTest extends WebTestCase
{
    public function testFooAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/foo');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertJsonResponse($client->getResponse());
    }
}

Which is in the following path inside the tests directory:

.
└── AppBundle
    └── Controller
        ├── DefaultControllerTest.php
        └── FooControllerTest.php

The tests run without any kind of problem, and I actually discovered this error by chance. If I remove that file and any references to it from the tests then I can check debug:autowiring without any hassle. However I can't figure out what I am missing here. I guess it has something to do with file placement or something, but I don't really know. Can you lend me a hand please?

Also, if I didn't check that command, I wouldn't have noticed these errors. In order to avoid committing code to a repository which generates this kind of errors in the future, does Symfony log these errors somewhere? Or do I have to manually check every debug command?

Thank you in advance for your help.

Testing a controller with a form which has a field dynamicly generated

I have a form which has a dynamic field :

<?php

namespace AppBundle\Form;

//uses ...
class AnnonceType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('titre')
        ->add('description')
        ->add('groupeCompetence', EntityType::class, [
            'class'       => 'AppBundle\Entity\GroupeCompetences',
            'choice_label' => 'nom',
            'placeholder' => 'Sélectionnez votre type de service',
            ])
        ->add('prix')
        ->add('serviceADistance')
        ->add('ajouter', SubmitType::class);


        $formModifier = function (FormInterface $form, GroupeCompetences $groupeCompetences=null){
            $competences = null === $groupeCompetences ? array() : $groupeCompetences->getCompetences();

            $form->add('competence', EntityType::class, array(
                'class' => 'AppBundle\Entity\Competence',
                'choice_label' => 'nom',
                'placeholder' => 'Choisir une compétence',
                'choices' => $competences,
                ));
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {

                // this would be your entity, i.e. CompetenceChoisie
                $data = $event->getData();

                //var_dump($data);
                //die();

                $formModifier($event->getForm(), $data->getGroupeCompetence());
            }
            );

         $builder->get('groupeCompetence')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {

                $groupeCompetences = $event->getForm()->getData();

                $formModifier($event->getForm()->getParent(), $groupeCompetences);

            }
            );

    } 
}

I have this code in ajax :

<script>
  var $groupeCompetence = $('#requete_prestataire_groupeCompetence');
// When sport gets selected ...
$groupeCompetence.change(function() {
  // ... retrieve the corresponding form.
  var $form = $(this).closest('form');
  // Simulate form data, but only include the selected sport value.
  var data = {};
  data[$groupeCompetence.attr('name')] = $groupeCompetence.val();
  // Submit data via AJAX to the form's action path.
  $.ajax({
    url : $form.attr('action'),
    type: $form.attr('method'),
    data : data,
    success: function(html) {
      // Replace current position field ...
      $('#requete_prestataire_competence').replaceWith(
        // ... with the returned one from the AJAX response.
        $(html).find('#requete_prestataire_competence')
        );
      // Position field now displays the appropriate positions.
    }
  });
});
</script>

In fact, competences is generated dynamicly depending on GroupeCompetence.

And I want to test this in PHPUnit.

I tried this :

public function testIndexRechercheUtilisateurNonConnecte()
    {
        $crawler = $this->client->request('GET', '/');

        $form = $crawler->selectButton('requete_prestataire_Rechercher')->form();
        $form['requete_prestataire[groupeCompetence]'] = 2;
        $form['requete_prestataire[competence]'] = "";

        $crawler = $this->client->submit($form);
        $this->assertTrue($this->client->getResponse()->isRedirect());
        $client->followRedirect();

        /*$this->assertEquals(3, $crawler->filter('a [class = "btn-sm btn-primary"]')->count());*/


    }

The problem is that : $form['requete_prestataire[competence]'] is generated dynamicly as I said.

I want to be able to do the ajax request in the test, and then test the output.

How can I proceed ?

Thanks in advance

Junit testing - Actions for every test. How to minimize code?

I really didn't know how to describe it better in the title, but here it is explained:

I want to write tests for a Rest Api. Meaning: I log into the server for every test, run my call and log out. It would be way less code and more efficient, if I could somehow log into the server at the beginning of the test, do all my calls (still in seperate tests though) and then log out.

Is there a smart way to do this?

Thanks for every reply!

Supress Logger when testing

I wonder how to disable logging in Elixir when testing. In my current code I test for logger messages, so I don't want to disable it completely, but hide the messages until any test stop passing.

I'm using mix and ExUnit to manage and test my project.

mix test
Compiling 2 files (.ex)
.........
17:59:18.446 [warn]  Code seems to be empty
.
17:59:18.447 [warn]  Code doesn't contain HLT opcode
.
17:59:18.448 [warn]  Code doesn't contain HLT opcode

17:59:18.448 [error] Label error doesn't exist
.....

Finished in 0.07 seconds
16 tests, 0 failures

How to mock context(ActorContext)?

I am using TestKit to test the Akka Actors. I have a class Demo which has method getActorRef, which takes input as string and returns an ActorRef.

class Demo @Inject()(a: A. b: B, context: ActorContext) {
  def getActorRef(id: String): ActorRef
}

I have mocked A,B while creating object of Demo.Now i am facing issue how to mock context.

What i did to mock it ? val context = mock[ActorContext]

But it didn't work.

When attempting to test an html File object, it wont let me prepopulate it with a sample image?

I created Component I was wanting to test with Angular Dart's Framework.

When I create my test file, it seems though that I am having issues creating a sample file to test against.

In my hirerarchy, I have:

./bird.jpg
./image_uploader_po.dart
./image_uploaders_test.dart

and then in the code I have

test("testing against valid image upload", () async {
  File testImage = new File("./bird.jpg");  //improper constructor.
  fixture.update((Component com){
    com.imageFile = testImage;
  });
  uploaderPO = await fixture.resolvePageObject(Component);
});

The issue I have is that this is not the dart/io implementation of File, but instead the Html Implementation.

I was trying to determine what the best course of action would be for this, to open a file for read access to apply to the Component's implementation of File.

I was looking up filereader, but that relates to a file which exists, which is what I am having issues with.

Right now, File constructor is: File(List<Object> fileBits, String filename, [Map<String, Dynamic> options]); and ultimately didn't know what "fileBits" should be.

You can find the File Class I am using at: http://ift.tt/2CaJVQF

My desired end state is to use a sample image file to apply it to an Image Uploader Component.

Thank you.

Rust benchmark throws invalid memory reference error

I have some Rust code, and when I tried to do some testing, it give me good and correct results using normal tests, but when I run some benchmarks, it throws signal: 11, SIGSEGV: invalid memory reference error. Here is the same test both as a normal test and as a bench test.

// works fine!
#[test]
fn mul_test() {
    let r = Point::new();
    let x = Element::zero();
    let scalar: [u8; 48] = [// 48 values];

    let res = Point::mul(&r, &x, &scalar[..]);
    println!("{:?}", res);
}

// throws error
#[bench]
fn mul_bench(b: &mut Bencher) {
    let r = Point::new();
    let x = Element::zero();
    let scalar: [u8; 48] = [// 48 values];

    b.iter(|| Point::mul(&r, &x, &scalar[..]));
}

I know that there isn't much code provided here, but it is all nested structures, and posting all the code that is relevant for these tests, will require posting a huge amount of code. But as I said, the mul_test test works fine, and gives me correct result. But, the mul_bench benchmarks throws invalid memory reference error. What could possibly cause it?

testing web service GET using xamarin forms

I trying to get some basic user information, everything I get is Null , because either no data is coming in or something is missing . any help very much appreciated!

webservice class as follow :

public class InfoRegister

        {

            public string Name { get; set; }

            public string Email { get; set; }


    }  

webservice : is there any way to test this part without render it on a page . force execution or something?

public async Task<List<InfoRegister>> GetRegisterInfo( string token)
        {
            var response = new List<InfoRegister>();

            try
            {
                using (var httpClient = new HttpClient())
                {

                    InitClient(httpClient);

                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

                    var result = await httpClient.GetAsync("http://ift.tt/2bIH98B");

                    if (result.IsSuccessStatusCode)
                    {


                        var data = await result.Content.ReadAsStringAsync();
                        response = JsonConvert.DeserializeObject<List<InfoRegister>>(data);


                        System.Diagnostics.Debug.WriteLine("list" + data);
                    }
                }
                return response;
            }
            catch (Exception ex)
            {

            }

            return response;

        }

view model :

public ObservableCollection<InfoRegister> DisplayRegisterInfo { get; set; }

//here all I see is null , I dont even see the class properties like email or name. public static InfoRegister registerItems;

        public InfoRegister RegisterItems

        {

            get { return registerItems; }

            set

            {

                if (registerItems == value)

                    return;

                registerItems = value;

                OnPropertyChanged(this, new PropertyChangedEventArgs(nameof(RegisterItems)));

            }

        }

page cs:

mydataservice is the page where the webservice call is generated. , the first line is passing the token info and (GetRegisterInfo) is null

 public async  Task LoadInfo ()
            {
     var myInfo = await mydataservice.GetRegisterInfo(Token);
                DisplayRegisterInfo = new ObservableCollection<InfoRegister>(myInfo);


            } 

Error Message: "The email address you entered already belongs to an existing Apple account". How to have an email re-available for Sandbox testers?

I accidentally added the tester email in the bad section in the iTunes Connect. There is two options:

enter image description here

The one I choose by mistake is the User iTunes Connect, but I had to choose the Testers Sandbox.

enter image description here

What I want now is simply to add the tester in the good section, but I have an error message that says:"That email address is already associated to an existing Apple id."

enter image description here

How to get an email available to sandbox testers in iTunes Connect?

(I check that ticket, but it seems not to have solutions)

This is a test check on stack overflow

A tag is a keyword or label that categorizes your question with other, similar questions. Choose one or more (up to 5) tags that will help answerers to find and interpret your question.

Unit tests not compiling - Swift Xcode 9.2

I am learning some TDD for Swift and I came across an issue that Xcode wont compile my test code. I have no clue what could be wrong with this.

Other tests are working fine (also tests for "ListItem" and "Location"). I also closed Xcode many times and cleared Derived Data and even the project itself.

Below the screenshots of code and compile error. If I change the "ListItem" parameter in the method to "Any" (and change the type of the array also), it is compiling. But this is not the code I want without the specific type.

Thanks!

enter image description here

enter image description here

Regarding the Chrome and FF multi thread (Process) how to do load test with web protocol?

I wonder if some one solved the issue of browser multi thread with a request response script for load test

Bluetooth legacy feature testing challenges

We are testing Bluetooth over the device and we have to verify HSP profile (not HFP) for DUT, but available devices (which will be paired) in market support HFP which is a superset of HSP. So, difficult to test the HSP separately.

Similarly currently, devices support eScO links and devices which only support SCO link are not available (i didn't found).

how to verify these features?

mardi 26 décembre 2017

Junit 4 Testing coverage

I am unable to cover next method:

protected void dealDamage(int damage, String damageType) {
    this.setDamageDealt(damage);
    this.setDamageDealtType(damageType);
}

My test looks like this:

@Test
@Parameters({"30, physical"})
public void dealDamage(int damage, String damageType) throws Exception {
    this.creature.setDamageDealt(damage);
    this.creature.setDamageDealtType(damageType);
    assertEquals(this.creature.getDamageDealt(), 30);
    assertEquals(this.creature.getDamageDealtType(), "physical");
}

Test return success, but method is not covered at all. Where could be my mistake? Do I miss something?

Java testing if two void methods do the same

I have a class of paired void methods: each method has an equivalent one that should perform the same operation but in a different way. For example:

public void example1_1(){
    Integer i = new Integer(1);
}

public void example1_2(){
    Integer i = Integer.valueOf(11);
}

or

public void example2_1(){
    String result = "hello";
    for (int i = 0; i < 10; i++) {
        result += result;
    }
}

public void example2_2(){
    StringBuffer result = new StringBuffer("hello");
    for(int i = 0; i < 10; i++) {
        result += result;
    }
}

How can I test that the methods actually perform the same operations in pair?

How to Test an app in Alpha (Android) on a tablet

I have:

  • ... already tested an App in Alpha earlier. It seems there where conceptional changes meanwhile. (All gets better :-))
  • A new app version published for Alpha-Testing
  • I have a User in a testing group assigned and Testing Group is assigned to Alpha-Test
  • a link for testing the app and sent the link to the testing User.
  • User klicks on the link and brwoser opens. User signs-in with User-Account which is Member of the testing Group and gets the error-message: "To access this content you need to install and set up a web browser app."

So now I am unable or too stupid to simply test an app.

Can someone help me ?

How to exclude node_modules from create-react-app testing?

I want to make tests of my create-react-app using jest.

One of node_modules have test-error,

enter image description here

but I don't want jest to work with node_modules folder.

In the documentation I found configuration property "collectCoverageFrom" and tried to use itin my package.json:

  ....
  "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom ",
        "eject": "react-scripts eject"
  },
  "jest": {
        "collectCoverageFrom": [
            "!/node_modules/*"
         ]
  }

But there is nothing changed.

how to handle this popup on "http://ift.tt/LpUYtP"

title : handle popup box selenium code for handle div pop on same windows //package booking;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Dubai {
    public static void main(String[] args) throws Exception {
    System.setProperty ("webdriver.chrome.driver",
                       "C:\\Users\\miyau\\Desktop\\test\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://ift.tt/LpUYtP");
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//div[text()='Not Now']")).click();
        System.out.println("operation complit");
      }
 }
// snapshot of popup## Heading ## 

enter image description here

Right way to terminate testing mongodb server

We are using mongodb-prebuilt package for perform unit/integration testing (CI/CD) for the developed software, which performs interaction with mongodb database.

Common use case is following: launch testing mongodb server with prebuild package, perform test suite execution and then terminate server. First and second items are done easily, but third one causes some problems.

If mongodb-prebuilt-started server had not been terminated, test runner will hang forever. Instead, if try to terminate server by testConnection.command({ shutdown: 1 }) command, then unhandledRejection fires, which refers on closed connection - which of course had been forcefully closed by stopping the server.

Which is right way to dispose mongodb-prebuilt at afterAll test section? Test engine is jest, but it does not matter strongly.
Example code here:

import { MongodHelper } from 'mongodb-prebuilt';
import { MongoClient } from 'mongodb';

describe('Test suite', () => {
    let testConnection;
    beforeAll(async () => {
        const mongodHelper = new MongodHelper(['--port', "27018"]);
        await mongodHelper.run();
        testConnection = await MongoClient.connect(`mongodb://localhost:27018/admin`);
    });
    afterAll(async () => {
        await testConnection.dropDatabase();
        await testConnection.command({ shutdown: 1 });
        await testConnection.close();
        testConnection = null;
    });
    /* Here follows some test suite that uses testConnection  */
}

There was some attempts to solve problem:

1) Don't await testConnection.command({ shutdown: 1 })-generated promise, and instantly initiate client connection closing - it works on some machines, but most likely depends on execution speed, so works unstable.

2) Because of client connection termination at the end of the tests does not matter strongly - it's possible to setup process.on('unhandledRejection', ...) handler in afterAll section and just mute exception - works well, but seems to be ideologically incorrect

So, maybe is there stereotypical solution for original task?

IMPORTANT NOTE: suggesting use some mock packages instead live mongodb is not appropriate at all, since developed software is specific adapter for mongodb and should respect all aspects of live database, including timings, admin commands and so on

Roboelectric slow and gives warnings

This is my first time using Roboelectric. Writing my first test which is just a simple test asserting the title of the Activity takes about 18s to execute and gives me the following warnings:

WARNING: no system properties value for "ro.control_privapp_permissions"
WARNING: no system properties value for "ro.crypto.state"
WARNING: no system properties value for "ro.crypto.type"

What are those warnings? and even if I ignore the warnings, should it really take 18s to execute this small test?

This is the test:

@Test
public void titleIsCorrect() throws Exception {
    Activity activity = Robolectric.setupActivity(MainActivity.class);
    assertTrue(activity.getTitle().toString().equals("Title"));
}

how to select drop-down options in cucumber rails

how to select drop-down options in cucumber rails browser.select(:xpath, '//[@id="login_form"]/div[2]/div[1]/div[4]/div/select').click browser.select(:xpath, '//[@id="login_form"]/div[2]/div[1]/div[4]/div/select/option[11]').click

Perl 6: automated testing of terminal-based programs

How could I automate interactions with command line programs that expose a text terminal interface with Perl 6 for testing purposes?

lundi 25 décembre 2017

Angular2/ionic2 testing: expected spy push to have been called

I am currently testing an ionic application. The problem is that the test fails, the error log is: "Expected spy push to have been called.". I really do not know why it does not work since I can get the element and I can click it. The console log does display that the size is. This means that it does contain that one button.

HTML :

<ion-header>
  <ion-navbar>
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>


<ion-content class="master">
    <div class="loginWindow">
      <ion-item>
        <ion-label fixed>Sign in</ion-label>
      </ion-item>
      <ion-item>
        <ion-label fixed>Email</ion-label>
        <ion-input type="email" name="email"></ion-input>
      </ion-item>

      <ion-item>
        <ion-label fixed>Password</ion-label>
        <ion-input type="password" name="password"></ion-input>
      </ion-item>
      <ion-item>
        <div padding>
          <button ion-button (click)="doLogin()" id="loginButton" class="loginButtons" color="avioBlue" block>Sign in</button> <-- this is the button 
        </div>
      </ion-item>
    </div>
</ion-content>

And as for the test file:

it('should be able to navigate to home page', () => {

    let navCtrl = fixture.debugElement.injector.get(NavController);
    spyOn(navCtrl, 'push');

    const buttons = fixture.debugElement.queryAll(By.css("button"));
    console.log(buttons);
    de = buttons[0];
    de.triggerEventHandler('click', null);

    expect(navCtrl.push).toHaveBeenCalled();
  });

how to enable memory profiler only when testing in python?

I am using memory_profiler in python and profiling some piece of code. But I only want that to enable when testing is happening, like the function is being invoked from a test-suite. I don't want the profiler being enabled when code is running in production. Is there any way to do that?

Or I am open to generic suggestion like how to enable decorators only when the testing is happening.

Example code -

from memory_profiler import profile

@profile(precision=4)
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    del b
    return a

test C program with some inputs

I wrote a program in c and I want to try it with some inputs. The inputs are not numbers so I cant use a for loop or something like this in the code. So I want to write a file with inputs and give it to the program so it will take every time (it waits to input) 1 line from the text file or something like this, is it possible?

Thank you in advance.

Node.js Mocha Sequelize Error ConnectionManager.getConnection was called after the connection manager was closed

There are 2 mocha test files:

  1. Creates a server and pings it using chai just to check if it's
    working
  2. Creates a server and tests user insertion into database (sequelize postgres)

Both of these servers initialize a database connection.

When ran independently both of them pass, when ran together the second one fails with the following error:

Error ConnectionManager.getConnection was called after the connection manager was closed

Looking at the console, connection with the database is established 2 times for each test, but still acts as a single pool.

# db/index.js

global.TABLE_USERS = 'users';

const Promise = require('bluebird');
const Sequelize = require('sequelize');
const config = require('./../config');
const User = require('./User');

/**
 * @return {Promise}
 */
const connect = () => {
    return new Promise((resolve, reject) => {
        let sequelize = new Sequelize(config.postgres.database, config.postgres.user, config.postgres.password, {
            host: config.postgres.host,
            dialect: 'postgres',
            pool: {
                max: 5,
                min: 0,
                acquire: 30000,
                idle: 10000
            },
            define: {
                underscored: false,
                freezeTableName: false,
                charset: 'utf8',
                dialectOptions: {
                    collate: 'utf8_general_ci'
                }
            },
        });

        let user = User(sequelize);

        sequelize
            .authenticate()
            .then(() => {
                resolve({
                    User: user,
                    sequelize: sequelize
                })
            })
            .catch(err => {
                console.error('Couldn\'t authenticate');
                reject(err)
            })
    });
};

module.exports.connect = connect;

Main server module:

const express = require('express');
const bodyParser = require('body-parser');
global.Promise = require('bluebird');
let routing = require('./routing');
const config = require('./config');
const middleware = require('./middleware');
let database = require('./db');
let Repositories = require('./repositories');
let Services = require('./services');
let Controllers = require('./controllers');
const Promise = require('bluebird');

/**
 * @property {http.Server} this.app
 */
class Server {

    constructor() {
        this.app = express();
    }

    /**
     * @param {Function} beforeHook
     *
     */
    init(beforeHook = null) {
        return this._initDatabaseConnection()
            .then(() => {
                this._initContainer(beforeHook);
                this._initRoutes();
                return this._initServer()
            });
    }

    /**
     *
     * @param {Function} beforeHook
     * @private
     */
    _initContainer(beforeHook) {
        this.container = {};
        // Modify for testing before starting
        if (typeof beforeHook === 'function') beforeHook(this);
        this.container = Repositories(this.database);
        this.container = Services(this.container);
        this.controllers = Controllers(this.container);
    }

    /**
     *
     * @private
     */
    _initRoutes() {
        this.app.use(bodyParser.json());
        middleware.handleCors(this.app);
        this.app.use(routing({...this.controllers, ...this.services}));
        middleware.handleErrors(this.app);
    }

    /**
     *
     * @private
     *
     * @return {Promise}
     */
    _initServer() {
        return new Promise((resolve, reject) => {
            this.server = this.app.listen(config.app.port, () => {
                console.log(`Server started listening in ${config.app.env} on port ${config.app.port}`);
                resolve(this)
            });
        });
    }

    /**
     *
     * @return {Promise}
     * @private
     */
    _initDatabaseConnection() {
        return database.connect()
            .then(connection => {
                this.database = connection;
                console.log('Connected to the database');

                return Promise.resolve()
            })
    }

    /**
     * @return {Promise}
     */
    close() {
        this.server.close();
        return this.database.sequelize.close();
    }
}

module.exports = Server;

First test case

const assert = require('assert');
const chai = require('chai'),
    expect = chai.expect,
    chaiHttp = require('chai-http');

chai.use(chaiHttp);

const Server = require('../../src/Server');

describe('Server app test', () => {

    let server;

    before(async () => {
        server = await (new Server()).init();
    });

    after(async () => {
        await server.close();
    });

    it('should say respond it\'s name', async () => {
        let pingServer = () => {
            return new Promise((resolve, reject) => {
                chai.request(server.server)
                    .get('/')
                    .end((err, res) => {
                        expect(err).to.be.null;
                        expect(res).to.have.status(200);
                        resolve(res.body)
                    });
            });
        };

        let res = await pingServer();
        assert.equal(res.msg, 'API server');
    });
});

Second test case, UserControllerTest

const assert = require('assert');
const chai = require('chai'),
    expect = chai.expect,
    chaiHttp = require('chai-http');

chai.use(chaiHttp);

const sinon = require('sinon');
const Promise = require('bluebird');
const Response = require('./../../src/lib/RequestHelper');
const UserValidation = require('./../../src/validation/UserValidation');
const Server = require('./../../src/Server');
const ReCaptchaService = require('./../../src/services/ReCaptchaService');
const ValidationError = require('./../../src/errors/ValidationError');


describe('/users/signup', () => {

    describe('valid reCaptcha scenario', () => {
        let server, reCaptchaServiceStub;

        before(async () => {
            reCaptchaServiceStub = sinon.stub(ReCaptchaService.prototype, 'authenticate').returns(true);

            function setReCaptchaServiceStub(server) {
                server.services = {ReCaptchaService: new reCaptchaServiceStub()};
            }

            server = await (new Server()).init(setReCaptchaServiceStub);
        });

        after(async () => {
            reCaptchaServiceStub.restore();
            await server.database.User.destroy({where: {}});
            await server.close();
        });

        beforeEach(async () => {
            await server.database.User.destroy({where: {}});
        });

        it('should allow user to register', async () => {

            let data = {email: 'myemail@gmail.com', password: '1234'};
            data[UserValidation.CAPTCHA_RESPONSE] = 'captcha_token';

            let signUp = (data) => {
                return new Promise((resolve, reject) => {
                    chai.request(server.server)
                        .post('/users/signup')
                        .send(data)
                        .end((err, res) => {
                            console.log(res.body)
                            expect(err).to.be.null;
                            expect(res).to.have.status(Response.STATUS_OK);
                            resolve(res.body)
                        });
                });
            };

            let res = await signUp(data);
            expect(res.token).to.be.a('string');
        });
    });

    describe('invalid reCaptcha scenario', () => {
        let server, reCaptchaServiceStub;

        before(async () => {
            reCaptchaServiceStub = sinon.stub(ReCaptchaService.prototype, 'authenticate')
                .onCall()
                .throws(new ValidationError('some err'));

            function setReCaptchaServiceStub(server) {
                server.container.ReCaptchaService = new reCaptchaServiceStub()
            }

            server = await (new Server()).init(setReCaptchaServiceStub);
        });

        after(async () => {
            reCaptchaServiceStub.restore();
            await server.close();
        });

        beforeEach(async () => {
            await server.database.User.destroy({where: {}});
        });

        it('should send a bad request on invalid reCaptcha', async () => {

            let data = {email: 'myemail@gmail.com', password: '1234'};
            data[UserValidation.CAPTCHA_RESPONSE] = 'random_token';

            let signUp = (data) => {
                return new Promise((resolve, reject) => {
                    chai.request(server.server)
                        .post('/users/signup')
                        .send(data)
                        .end((err, res) => {
                            expect(err).to.not.be.null;
                            expect(res).to.have.status(Response.STATUS_BAD_REQUEST);
                            resolve(res.body);
                        });
                });
            };

            let res = await signUp(data);
            expect(res.err).to.equal(UserValidation.ERR_INVALID_RECAPTCHA);
        });
    });
});

Mapreduce MRUnit not passes test with correct output

I try to test my mapper in MaprReduce job with such test:

    @Test
    public void testMapper_1() throws IOException {
    mapDriver.withInput(new LongWritable(),
            new Text("ip981 - - [26/Apr/2011:14:52:47 -0400] \"GET /faq/ide.jpg HTTP/1.1\" 200 40416 \"http://host2/faq/\" \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16\""));
    mapDriver.withInput(new LongWritable(),
            new Text("ip987 - - [26/Apr/2011:14:52:50 -0400] \"GET /faq/scsi.gif HTTP/1.1\" 200 953 \"http://host2/faq/\" \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13\""));

    MetricWritable value1 = new MetricWritable();
    value1.setValues(40416, 1.0);
    mapDriver.withOutput(new Text("ip981"), value1);

    MetricWritable value2 = new MetricWritable();
    value2.setValues(953, 1.0);
    mapDriver.withOutput(new Text("ip987"), value2);

    mapDriver.runTest();
    }

And recieve from MRUnit following error:

java.lang.AssertionError: 2 Error(s): (Missing expected output (ip981, 1.0  40416) at position 0, got (ip981, 1.0   40416)., Missing expected output (ip987, 1.0    953) at position 1, got (ip987, 1.0 953).)

My job works correctly with real input log. I suspect that problem is in whitespace and tab characters between fields of value. But I have no idea how to fix it. Could somebody help me to find way of fixing? Thank you.

Using QuickCheck with structures in Rust

I want to use QuickCheck to test a function that makes use of structs that I have created. I see I need to implement the Arbitrary trait for these types. I have something like this:

#[cfg(test)]
use quickcheck::{Arbitrary, Gen, QuickCheck};

const NUM_WORDS: usize = 12;

#[derive(Copy, Clone)]
pub struct Element(pub(crate) [u64; NUM_WORDS]);

#[cfg(test)]
impl Arbitrary for Element {
    fn arbitrary<G: Gen>(g: &mut G) -> Element {
        let e: [u64; NUM_WORDS] = g.gen::<[u64; NUM_WORDS]>();
        Element(e)
    }
}

#[derive(Clone, Debug)]
struct ExtensionElement {
    A: Element,
    B: Element,
}

#[cfg(test)]
impl Arbitrary for ExtensionElement {
    fn arbitrary<G: Gen>(g: &mut G) -> ExtensionElement {
        let a = g.gen::<Element>();
        let b = g.gen::<Element>();
        ExtensionElement { A: a, B: b }
    }
}

When I try to use ExtensionElement inside a QuickCheck test, I get the following error message inside the arbitrary function for ExtensionElement:

the trait 'rand::Rand' is not implemented for 'Element'

How I can implement the Arbitrary trait so that I can use my structs with QuickCheck?

How to guarantee corner cases in property based testing

Recently, I'm quite excited when reading about the idea of property based testing.

But I have 1 question that I still cannot find the answer anywhere:

How can property based testing ensures that it will test the corner cases every time?

To be more specific, let say I'm using ScalaCheck to test my division function:

def divide(a: Int, b: Int): Int

As the test cases will be generated randomly, how can I be sure that ScalaCheck will check the case where b = 0 every time?

dimanche 24 décembre 2017

Code Coverage and Ternary Operators

Consider we have this function under test located in the module.py:

def f(a, b):
    return (a - b) if a > b else 1 / 0

And, we have the following test case in the test_module.py:

from unittest import TestCase

from module import f


class ModuleTestCase(TestCase):
    def test_a_greater_than_b(self):
        self.assertEqual(f(10, 5), 5)

If we run tests with pytest with the enabled "branch coverage" with the HTML output reporting:

pytest test_module.py --cov=. --cov-branch --cov-report html

The report is going to claim 100% branch coverage with all the "partial" branches covered:

enter image description here

But, we clearly have not covered the else 1 / 0 part at all.

Is there a way to improve reporting to see the non-covered parts of the ternary operators?

Php - how to fail 'json_encode'?

Trying to test a method that is doing a json_encode and throwing an exception if the encode fails. However, whatever I throw at json_encode it successfully encodes. Any idea what would be something simple to have it fail?

Unit test for services

I have a services class UserServiceImpl with a method creatUser()

@Autowired
    private UserRepository  userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Override
    public User createUser(User user, Set<UserRole> userRoles) throws DataAccessException {
        User localUser = userRepository.findByUsername(user.getUsername());

        if (localUser != null) {
            LOG.info("user {} already exists. Nothing will be done.", user.getUsername());
        } else {
            for (UserRole ur : userRoles) {
                roleRepository.save(ur.getRole());
            }
            user.getUserRoles().addAll(userRoles);

            localUser = userRepository.save(user);
        }
        return localUser;
    }

I am trying to test this with unit test but don't know how to go about it . Any help would suffice .here is my test case .

 @Test
    public void createUserTest() {
        UserServiceImpl usr = new UserServiceImpl();
        User user = new User();

        String[] SET_VALUES = new String[]{"ADMIN"};

        UserRole userRole = new UserRole();

        userRole.setRole(role);
        Set<String> myset = new HashSet<String>(Arrays.asList(SET_VALUES));

        ObjectMapper objectMapper = new ObjectMapper();

        String[] GPXFILES1 = myset.toArray(new String[myset.size()]);

        usr.createUser(user,myset.toArray());


    }

right now I am stuck here , and I don't know how to pass a set as a parameter input

What is artificial intelligence ? How it's help or change on software testing field?

I am looking for some new technologies in software testing. Could you please explain what's is artificial intelligence ? How to start learning about this ? What are all pre requisite required ? How it's helpful in software testing ? .. please explain in simplest way

samedi 23 décembre 2017

nock handles fetch req but does not prevent http call

I am using nock to intercept a fetch call to https://www.youtube.com/oembed?url=https://youtu.be/m4hklkGvTGQ . Like so:

it(`properly responds to YouTube URL ${url}`, async () => {
    nock('https://www.youtube.com')
        .get('/oembed')
        .query(true)
        .reply(200, remoteResponse);
    const youTube = new YouTube(url);
    const response = await youTube.getResponse(); // this contains the fetch call
    expect(response).toEqual(expectedResponse);
    nock.restore();
});

I see that nock properly intercepts my fetch because

  • If I change the remoteResponse (see line 5, .reply(200, remoteResponse) my tests behave / fail as expected
  • If I change the intercepting url from https://www.youtube.com to http://ift.tt/2l0LBUX, nock tells me it did not catch a fetch request.

However, if I switch off my WiFi and run my tests I can see that my application warns me about a failed HTTP request:

request to https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=m4hklkGvTGQ failed, reason: getaddrinfo ENOTFOUND www.youtube.com www.youtube.com:443

Also, when I run my tests, they take about 1 second (which already seems long), when I turn of my WiFi, they are done immediately.

I wonder why there are still http requests

vendredi 22 décembre 2017

Jest test case failing for React conditional

I am testing for the third conditional state error of the amount to equal a specific string, but when I run it I get an empty string.

Conditional:

if (!this.state.amount) {
    this.setState(() => ({ error: 'Please provide amount.' }));
}

Jest Test Case:

test('should render error for lack of amount', () => {
    const onSubmitSpy = jest.fn();
    const wrapper = shallow(<ExpenseForm expense={errors[1]} onSubmit={onSubmitSpy} />);
    expect(wrapper).toMatchSnapshot();
    wrapper.find('form').simulate('submit', {
        preventDefault: () => { },
    });
    expect(wrapper).toMatchSnapshot();
    console.log(wrapper.state('error'));
    expect(wrapper.state('error')).toBe('Please provide amount.');
}); 

Error array index:

id: '5',
description: 'Gas',
note: '',
amount: '',
createdAt: moment(0).add(4, 'days').valueOf()

Ideally, this condition should test for the amount state to equal '' and give the error message of 'Please provide amount.'

Run tests with Spring reading data from a csv file

I'm trying to run a test multiple times, reading the input data needed from a csv file. I want to run the test for each line of the file.

I was going to do it manually, but I discovered Spring Batch. I'm new to spring batch, but I thought the following:

  • Create a spring boot application implementing command line runner.
  • In the run method, launch a spring batch job
  • This job would read the data from the csv file line by line, and for each line would run the @Test method for the data of the current line.

Is this approach ok? Is there a better way to do it? Can you provide any example code about how could it be done?

Thank you.

test mapDispatchToProps async actions

I am trying to test my mapDispatchToProps function when an asyncronous function is dispatched. I have read Dan Abramov's suggestions on how to test mapDispatchToProps and I am trying to test my code as such.

I am getting the error...

 TypeError: Cannot read property 'then' of undefined

Here is my test...

describe("mapDispatchToProps", () => {

    const dispatchSpy = jest.fn();
    const {signupUser} = mapDispatchToProps(dispatchSpy);

    it("should dispatch signupActions.signupUser()", () => {
        // mockAxios.onPost(endpoints.SIGNUP,{})
        //         .reply(200,'test_success');
        // tried with and without mockAxios

        signupUser({})
        const spyLastCall = dispatchSpy.mock.calls[0][0];
        expect(spyLastCall)
            .toEqual(signupActions.signupUser({}));
    })

})

The function that I want to test...

export const mapDispatchToProps = dispatch => {
    return { signupUser: (user) => {
        dispatch(signupActions.signupUser(user))
            .then((response) => {
                // do something on success
            }, (error) => {
                // do something on failure
            })
    }
}

I have already tested signupActions.signupUser and I know that it returns a promise. Here is the code...

export function signupUser(user) {
    return (dispatch) => {
        return dispatch(rest.post(SIGNUP,user))
            .then((response) => {
                return Promise.resolve(response);
            },(error) => {
                return Promise.reject(error)
            }
        )
}}

What am I doing wrong?

Ps: I also tried:

 const dispatchSpy = jest.fn().mockImplementation( () => {
    return p = new Promise((reject,resolve) => {
        resolve({})
    }) 
 }

with the same result

Ionic 3 testing cannot find button with by.css('button')

I am trying to get my button, which I have given the classname loginButton. My test constantly fails and the error says: "Expected the method spy push to have been called but it was never called". I am testing with karma and jasmine. Maybe it is because it cannot find the button ?

test class:

import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import {IonicModule, NavController} from 'ionic-angular';
import {StatusBar} from "@ionic-native/status-bar";
import {SplashScreen} from "@ionic-native/splash-screen";
import {NavMock} from "../../mocks";
import {By} from "@angular/platform-browser";
import {DebugElement} from "@angular/core";
import {LoginPage} from "./login";
import {MyApp} from "../../app/app.component";
import {HomePage} from "../home/home";

let comp: LoginPage;
let fixture: ComponentFixture<LoginPage>;
let de: DebugElement;

describe('Component: Login forward', () => {

  beforeEach(async(() => {

    TestBed.configureTestingModule({

      declarations: [MyApp, LoginPage],

      providers: [
        {
          provide: NavController,
          useClass: NavMock
        },
        [StatusBar],
        [SplashScreen]
      ],

      imports: [
        IonicModule.forRoot(MyApp)
      ]

    }).compileComponents();

  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(LoginPage);
    comp    = fixture.componentInstance;

  });

  afterEach(() => {
    fixture.destroy();
    comp = null;
    de = null;
  });

  it('should be able to navigate to home page', () => {

    let navCtrl = fixture.debugElement.injector.get(NavController);
    spyOn(navCtrl, 'push');

    de = fixture.debugElement.query((By.css('button')));
    de.triggerEventHandler('click', null);

    expect(navCtrl.push).toHaveBeenCalled();
  });
});

html page:

<ion-header>

  <ion-navbar>
    <ion-title>Login</ion-title>
  </ion-navbar>

</ion-header>


<ion-content class="master">
    <div class="loginWindow">
      <ion-item>
        <ion-label fixed>Sign in</ion-label>
      </ion-item>
      <ion-item>
        <ion-label fixed>Email</ion-label>
        <ion-input type="email" name="email"></ion-input>
      </ion-item>

      <ion-item>
        <ion-label fixed>Password</ion-label>
        <ion-input type="password" name="password"></ion-input>
      </ion-item>
      <ion-item>
        <div padding>
          <button ion-button (click)="doLogin()" class="loginButton" color="avioBlue" block>Sign in</button>
        </div>
      </ion-item>
    </div>
</ion-content>

Using nock to test POST request in async action creator

I am using nock to mock my asynchronous thunk action creators. Everything works as expected for GET requests, but I haven't been able to make a POST request work. I have read everything I can find online but nothing fixed my problem. I can see the response body in the failed test run. The issue is that there is no nock match for the url. Can anyone spot the problem?

Test file:

describe('#saveReminder', () => {
    it(`creates ${constants.actions.REQUEST_SAVE_REMINDER}
      and ${constants.actions.RECEIVE_SAVE_REMINDER}`, () => {

      data = { payload: 'payload' };

      nock(constants.paths.API_AUTHORITY)
        .post('api/prospect/add-reminder', {
          prospect: 1,
          reminder_datetime: '2017-12-22T18:42:00.000Z',
          description: 'description',
        })
        .reply(200, { data } )

      const expectedActions = [
        { type: constants.actions.REQUEST_SAVE_REMINDER },
        { type: constants.actions.RECEIVE_SAVE_REMINDER, data }
      ]

      return store.dispatch(actions.saveReminder({
        id: 1,
        description: 'description',
        date: moment(),
        time: moment(),
      })).then(() => {
        expect(store.getActions()).toEqual(expectedActions)
      })
    })
  })

Async action:

export function saveReminder({ id, description, date, time }) {
  return (dispatch) => {
    requestSaveReminder();
    return fetch(`${constants.paths.API_AUTHORITY}api/prospect/add-reminder`, {
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-Csrf-Token': Cookie.get('X-Csrf-Token'),
      },
      credentials: 'same-origin',
      method: 'POST',
      body: JSON.stringify(
        {
          prospect: id,
          reminder_datetime: moment(`${date.format('MM/DD/YYYY')} ${time.format('HH:mm')}`, 'MM/DD/YYYY HH:mm'),
          description,
        }
      ),
    }).then(response => {
      response.json();
    })
      .then(json => dispatch(receiveSaveReminder(json.data)))
      .catch(ex => dispatch(requestSaveReminderFailure(ex)));
  };
}

Test Failure:

Object {
    -     "type": "REQUEST_SAVE_REMINDER",
    +     "data": [FetchError: request to http://localhost:8080/api/prospect/add-reminder failed, reason: Nock: No match for request {
    +   "method": "POST",
    +   "url": "http://localhost:8080/api/prospect/add-reminder",
    +   "headers": {
    +     "accept": [
    +       "application/json"
    +     ],
    +     "content-type": [
    +       "application/json"
    +     ],
    +     "accept-encoding": [
    +       "gzip,deflate"
    +     ],
    +     "user-agent": [
    +       "node-fetch/1.0 (+http://ift.tt/18q0Hew)"
    +     ],
    +     "connection": [
    +       "close"
    +     ],
    +     "content-length": [
    +       89
    +     ]
    +   },
    +   "body": "{\"prospect\":1,\"reminder_datetime\":\"2017-12-22T18:56:00.000Z\",\"description\":\"description\"}"
    + }],
    +     "type": "REQUEST_SAVE_REMINDER_FAILURE",
        },
    -   Object {
    -     "data": Object {
    -       "payload": "payload",
    -     },
    -     "type": "RECEIVE_SAVE_REMINDER",
    -   },

The urls appear to match. Why does it say Nock: No match for request? Thanks!

scalamock and Skinny - overriding method addAttributeForCreation

I'm developing over Play 2.6.7, Skinny framework 2.5.0, Scalike 3.1.0 and scalamock 4.0.0.

My problem: I have a support class that extends of SkinnyCRUDMapper.

trait PersonSupport extends SkinnyCRUDMapper[Person]

The test has this declaration:

val personSupportMock = stub[PersonSupport]

When I wanna to run the test, it returns the following error:

Error:(16, 32) overriding method addAttributeForCreation in trait NoIdCUDFeature of type (namedValue: => (scalikejdbc.SQLSyntax, Any))services.PersonServiceTest.$anon.type;
 method addAttributeForCreation has incompatible type
  val personSupportMock = stub[PersonSupport]

Any idea of can I solve this problem?

Thanks!!

Lucas.