vendredi 31 mai 2019

multi matchs in espresso test android

I need to check view is display and is enabled.

  btn.check(matches(isDisplayed()))
            .check(matches(isEnabled()))

can I use an array for this?

for example:

 btn.check(matches(isDisplayed(),isEnabled()))

How do I package golang test helper code?

I have some test helper code in my golang library that I want to use when testing in various subpackages. However, I've hit a snag:

outer
|
+- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

To use the code in test_helpers_test.go, I have to import the outer package. But when I import the outer package from something_test.go, it complains "import cycle not allowed in test"

So I tried making a package for the shared test helpers:

outer
|
+- test
|  |
|  +- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

And now it complains "no non-test Go files in /home/karl/Projects/outer/test"

I don't want to call it test_helpers.go because it's part of my testing code, not my library code. I don't want to ship that code in the library.

How do I solve this?

How do i test did a message box shows up or not in unit testing?

i wanted to test, will the message box show up when my code request it. But i am not so sure what to assert or am i even doing the right thing.

public void btnSave_Click(object sender, EventArgs e)
        {
            if(txtFirstName.Text.Trim() != "" && txtLastName.Text.Trim() != "" && txtContact.Text.Trim() != "")
            {
                Regex reg = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); //only accepting proper email
                Match match = reg.Match(txtEmail.Text.Trim());
                if (match.Success)
                { using (SqlConnection sqlCon = new SqlConnection(connectionString)) // connecting info to database
                    {
                        sqlCon.Open();
                        SqlCommand sqlCmd = new SqlCommand("ContactAddorEdit", sqlCon);
                        sqlCmd.CommandType = CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@PhoneBookID", PhoneBookID); //connecting each value to database
                        sqlCmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Contact", txtContact.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
                        sqlCmd.ExecuteNonQuery(); // executeing the query in database
                        MessageBox.Show("Submitted successfully"); // showing message when success
                        Clear(); // clearing the form
                        GridFill();// refreshing the table
                    }
                }
                else
                {
                    MessageBox.Show(" Please enter a valid Email"); // Showing MEssage when email is not valid
                }
            }
            else
            {
                MessageBox.Show("Please fill Mandatory fields"); // if no input this message will show
            }

        }

So if the text box got a empty string there will be an message box pops up and say "Please fill Mandatory fields"

and here is the test that i am trying write


        [TestMethod]
        public void TestMethod1()
        {
            Form1 form1 = new Form1();
            form1.txtFirstName.Text = "";
            Assert.IsTrue(MessageBox.Show("Please fill Mandatory fields") ;
        }

What kind of assert should and use and how do i write it? Can i test it like this? Thank you

Repeat test in pytest but regard all repetitions together as one test only

I want to repeat a test and it should fail if one of those repetitions fails. So basically:

def test_example():
    for _ in range(5):
        assert random.randint(0, 1)

Is there a better way to do this? Since I'd have to modify the test function test_example itself for this (insert the for loop), I'd rather just have a decorator to do the same.

However, if I use

@pytest.mark.parametrize("reps", range(5))
def test_example(reps):
    assert random.randint(0, 1)

or

@pytest.mark.repeat(5)
def test_example():
    assert random.randint(0, 1)

I get a total of 5 tests - but I want 1 test result for all 5 tests together.

Stubbing out method with ArrayList/List param fails when using any() or anyList()

I have a java class that I am trying to test:

class Blah{
        public Blah(){

        }
        public String testMe(List<String> s){
            return new String("hello "+s.get(0));
        }


        public String testMeString(String s){
            return new String("hello "+s);
        }


    }

I am unable to test the testMe method successfully. For example I have tried:

    @Test
    public void testTestMe(){
        Blah blah = spy(new Blah());
        ArrayList<String> l = new ArrayList<String>();
        l.add("oopsie");
        when(blah.testMe(Matchers.any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMe(l));

This returns a NullPointerException. I have also tried any(List.class), any(ArrayList.class). I have also tried using anyList() but this gives me an IndexOutOfBounds error. What am I doing wrong? Interestingly, my testMeString works fine. If I do

@Test
    public void testTestMeString(){
        Blah blah = spy(new Blah());
        when(blah.testMeString(any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMeString("lala"));
}

the tests pass with any() and any(String.class).

TestCafe - Checking if the hyperlink is working - redirection to an external email provider

On the website is e-mail address (hyperlink) e.g. example@gmail.com, in one of the test scenarios I would like to click on this link and check if the user is redirected to an external e-mail provider, e.g. outlook. Can I do something like that in TestCafe?

HttpServletRequest is null when testing RestController in Spring

I am developing a Spring webservice and I need to read data & set them as a Session attribute in an interceptor. Everything works fine when I test the endpoints using an external client. However, I get a NullPointerException when I try the code below:

@RunWith(SpringRunner.class)
@WebMvcTest(AccountController.class)
public class AccountControllerTest {

private MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@MockBean
private IncomingInterceptor incomingInterceptor;

@MockBean
private AccountService accountService;

@MockBean
private FileStoreService fileStoreService;

@MockBean
private HttpServletRequest request;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws Exception {
    JsonObject root = new JsonObject();
    root.add("body", gson.toJsonTree(account));

    Mockito.when(accountController.addAccount()).thenReturn(new ResponseEntity<>(1L, HttpStatus.OK));

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/account/register")
            .content(root.toString())
            .characterEncoding("utf-8")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();

    String contentAsString = mvcResult.getResponse().getContentAsString();
    System.out.println("contentAsString = " + contentAsString);
}
}

Everyting works as expected when the attributes are set in the interceptor but when I try to access them in AccountController an exception is thrown. I have already tried to use MockMvcRequestBuilders but it wasn't working either.

The code to access attributes:

 JsonObject body = (JsonObject) request.getSession().getAttribute("body");           

Thanks in advance!

Jest Testing import a basic function and run test

I want to implement jest to a small project written with Javascript ES6. Below, you can see how I tried to implement one function. Where do you think I do wrong?

I have function that adds the arguments

function findTotal(a, b) {
  return a + b;
}
}

and I export it

export default { findTotal };

Then I import it in my test file

import { findTotal } from "../src/assessment";

Then the test itself

import { findTotal } from "../src/assessment";


describe("The Total", () => {

  it("should find total", () => {

    expect(findTotal(1, 2)).toBe(3);
  });

});

Result


     ● The total › should find total

    TypeError: (0 , _assessment.findTotal) is not a function

      at Object.<anonymous> (test/assessment.test.js:5:38)
          at new Promise (<anonymous>)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

How do you test locally with Neptune?

I am trying to test our neptune db using gremlin. I have come up short with way to test locally. What are my options?

Currently just testing in real time. This is obviously not very effecient.

Jasmine marbles testing NGRX effects

I'm trying to test an NGRX effect using jasmine-marbles but the response I get from effects.myEffect$ appears to have nested operators. What I was expecting was an observable returning a single, flat action. Any help or input would be greatly appreciated.

 it('Test Effect', async(inject([ServicesStub],
    async (servicesStub: ServicesStub) => {

      const payloadRequest = new RequestActionPayload();
      const actionRequest = new RequestAction(payloadRequest);

      const payloadResponse = new ResponseActionPayload();
      const actionResponse = new ResponseActionPayload(payloadResponse);

    const source = hot('a|', { a: actionRequest});

    const effects = new NewEffectService(new Actions(source), ...);

    const expected = cold('-a', { a: actionResponse });
    expect(effects.myEffect$).toBeObservable(expected);}
)));

my effect looks like this:

  @Effect()
  myEffect$ = this.actions$
    .pipe(
      ofType(actions.REQUEST_ACTION),
      map((action: actions.RequestAction) => action.payload),
      switchMap(payload => ... do some work),
      map(([a, b]) => new actions.ResponseAction(new actions.ResponseActionPayload(...)))
    );

my package.json looks like:

"jasmine-marbles": "^0.5.0"
"rxjs": "^6.5.1",
"@ngrx/effects": "^7.4.0",
"@ngrx/router-store": "^7.4.0",
"@ngrx/store": "^7.4.0",
"@ngrx/store-devtools": "^7.4.0",

nested observers/source:

enter image description here

Undefined method Class::create()

When I debug my test to see how the passport route work

<?php


namespace Tests\Feature\Auth;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Passport\Client;
use Tests\TestCase;
use App\Directory;
use App\Event;

class AuthTest extends TestCase
{
    use RefreshDatabase;
    /**
     * @test
     */
    public function can_authenticate()
    {
        $response = $this->json('POST', '/auth/token', [
            'email' => $this->create('User', [], false)->email,
            'password' => 'secret'
        ]);
        $response->assertStatus(200)
            ->assertJsonStructure(['token']);
    }
}

I receive the following error :

Error : Call to undefined method Tests\Feature\Auth\AuthTest::create() /home/amine/Apps/PassportV2/tests/Feature/Auth/AuthTest.php:28

how can I fix it?

thank you in advance

How to purge test sessions in Botium

I'm trying to run Test Set but it looks like it is stucked. All 5 agents are in use and I cannot delete them. Tests fail on ESOCKETTIMEDOUT. I could run same test without problems before.

I tried to click on Send cancellation request"" to Test Session in danger zone to kill it, but I still can't delete agents.

Botium agents pic

Log from Botium:

2019-05-31T08:31:13.892Z: Job queued for execution
2019-05-31T08:31:13.886Z: 2019-05-31T08:31:13.378Z botium-box-worker-runtestcases Started processing, JobId #952.

2019-05-31T08:31:14.077Z: 2019-05-31T08:31:13.382Z botium-BotDriver Loaded Botium configuration file ./botium.json

2019-05-31T08:31:14.143Z: 2019-05-31T08:31:13.388Z botium-BotDriver BuildCompiler: Capabilites: { PROJECTNAME: 'TM new - Test Session',
  TEMPDIR: 'botiumwork',
  CLEANUPTEMPDIR: true,
  WAITFORBOTTIMEOUT: 10000,
  SIMULATE_WRITING_SPEED: false,
  DOCKERCOMPOSEPATH: 'docker-compose',
  DOCKERMACHINEPATH: 'docker-machine',
  DOCKERMACHINE: false,
  DOCKERIMAGE: 'node:boron',
  DOCKERUNIQUECONTAINERNAMES: false,
  DOCKERSYSLOGPORT_RANGE: '47100-47299',
  BOT_HEALTH_STATUS: 200,
  SLACK_PUBLISHPORT_RANGE: '46100-46299',
  FACEBOOK_PUBLISHPORT_RANGE: '46300-46499',
  FACEBOOK_SEND_DELIVERY_CONFIRMATION: true,
  BOTFRAMEWORK_PUBLISHPORT_RANGE: '46500-46699',
  BOTFRAMEWORK_WEBHOOK_PORT: 3978,
  BOTFRAMEWORK_WEBHOOK_PATH: 'api/messages',
  BOTFRAMEWORK_CHANNEL_ID: 'facebook',
  SIMPLEREST_PING_RETRIES: 6,
  SIMPLEREST_PING_TIMEOUT: 10000,
  SIMPLEREST_PING_VERB: 'GET',
  SIMPLEREST_METHOD: 'GET',
  WEBSPEECH_SERVER_PORT: 46050,
  WEBSPEECH_LANGUAGE: 'en-US',
  WEBSPEECH_CLOSEBROWSER: true,
  SCRIPTING_TXT_EOL: '\n',
  SCRIPTING_XLSX_EOL_SPLIT: '\r',
  SCRIPTING_XLSX_EOL_WRITE: '\r\n',
  SCRIPTING_XLSX_STARTROW: 2,
  SCRIPTING_XLSX_STARTCOL: 1,
  SCRIPTING_NORMALIZE_TEXT: false,
  SCRIPTING_ENABLE_MEMORY: false,
  SCRIPTING_MATCHING_MODE: 'includeLowerCase',
  SCRIPTING_UTTEXPANSION_MODE: 'all',
  SCRIPTING_UTTEXPANSION_RANDOM_COUNT: 1,
  SCRIPTING_MEMORYEXPANSION_KEEP_ORIG: false,
  RETRY_USERSAYS_ONERROR_REGEXP: [],
  RETRY_USERSAYS_NUMRETRIES: 1,
  RETRY_USERSAYS_FACTOR: 1,
  RETRY_USERSAYS_MINTIMEOUT: 1000,
  ASSERTERS:
   [ { ref: 'HASLINK',
       src: 'botium-asserter-basiclink',
       global: false,
       args: null } ],
  LOGIC_HOOKS: [],
  USER_INPUTS: [],
  CONTAINERMODE: 'webdriverio',
  WEBDRIVERIO_URL: 'https://chat.t-mobile.cz/chat/',
  WEBDRIVERIO_PROFILE: '',
  WEBDRIVERIO_INPUT_ELEMENT: '<input />',
  WEBDRIVERIO_INPUT_ELEMENT_VISIBLE_TIMEOUT: 10000,
  WEBDRIVERIO_OUTPUT_ELEMENT:
   "//div[@class='gaid-text-message gaid-text-message--isBot'][position()=last()-1]//p",
  WEBDRIVERIO_IGNOREUPFRONTMESSAGES: false,
  WEBDRIVERIO_USERNAME: '',
  WEBDRIVERIO_PASSWORD: '',
  WEBDRIVERIO_SCREENSHOTS: 'onstop',
  FBPAGERECEIVER_REDISURL: { port: '6379', host: 'redis', db: 0, options: {} },
  WEBDRIVERIO_OPTIONS:
   { desiredCapabilities: { browserName: 'chrome', name: 'TM new - Test Session' },
     protocol: 'http',
     host: '192.168.99.100',
     port: '4444',
     path: '/wd/hub' } }

2019-05-31T08:31:14.169Z: 2019-05-31T08:31:13.393Z botium-ScriptingProvider Using matching mode: includeLowerCase

2019-05-31T08:31:14.214Z: 2019-05-31T08:31:13.396Z botium-asserterUtils Loaded Default asserter - [ 'BUTTONS',
  'MEDIA',
  'PAUSE_ASSERTER',
  'ENTITIES',
  'ENTITY_VALUES',
  'INTENT',
  'INTENT_CONFIDENCE' ]

2019-05-31T08:31:14.251Z: 2019-05-31T08:31:13.402Z botium-asserterUtils Loaded Default logic hook - [ 'PAUSE',
  'WAITFORBOT',
  'SET_SCRIPTING_MEMORY',
  'CLEAR_SCRIPTING_MEMORY',
  'INCLUDE' ]

2019-05-31T08:31:14.339Z: 2019-05-31T08:31:13.403Z botium-asserterUtils Loaded Default user input - [ 'BUTTON', 'MEDIA', 'FORM' ]

2019-05-31T08:31:14.396Z: 2019-05-31T08:31:13.407Z botium-asserterUtils Trying to load HASLINK asserter from botium-asserter-basiclink

2019-05-31T08:31:14.433Z: 2019-05-31T08:31:13.410Z botium-asserterUtils Loaded HASLINK SUCCESSFULLY

2019-05-31T08:31:14.470Z: 2019-05-31T08:31:13.504Z botium-box-worker-runtestcases found 1 convos ...

2019-05-31T08:31:14.512Z: 2019-05-31T08:31:13.504Z botium-box-worker-runtestcases batchNum: 1 batchCount: 1 convosPerBatch: 1 batchStart: 0 batchEnd: 0 batchLength: 1

2019-05-31T08:31:14.548Z: 2019-05-31T08:31:13.507Z botium-BotDriver Build - Botium Core Version: 1.4.14

2019-05-31T08:31:14.586Z: 2019-05-31T08:31:13.510Z botium-BotDriver Build - Capabilites: { PROJECTNAME: 'TM new - Test Session',
  TEMPDIR: 'botiumwork',
  CLEANUPTEMPDIR: true,
  WAITFORBOTTIMEOUT: 10000,
  SIMULATE_WRITING_SPEED: false,
  DOCKERCOMPOSEPATH: 'docker-compose',
  DOCKERMACHINEPATH: 'docker-machine',
  DOCKERMACHINE: false,
  DOCKERIMAGE: 'node:boron',
  DOCKERUNIQUECONTAINERNAMES: false,
  DOCKERSYSLOGPORT_RANGE: '47100-47299',
  BOT_HEALTH_STATUS: 200,
  SLACK_PUBLISHPORT_RANGE: '46100-46299',
  FACEBOOK_PUBLISHPORT_RANGE: '46300-46499',
  FACEBOOK_SEND_DELIVERY_CONFIRMATION: true,
  BOTFRAMEWORK_PUBLISHPORT_RANGE: '46500-46699',
  BOTFRAMEWORK_WEBHOOK_PORT: 3978,
  BOTFRAMEWORK_WEBHOOK_PATH: 'api/messages',
  BOTFRAMEWORK_CHANNEL_ID: 'facebook',
  SIMPLEREST_PING_RETRIES: 6,
  SIMPLEREST_PING_TIMEOUT: 10000,
  SIMPLEREST_PING_VERB: 'GET',
  SIMPLEREST_METHOD: 'GET',
  WEBSPEECH_SERVER_PORT: 46050,
  WEBSPEECH_LANGUAGE: 'en-US',
  WEBSPEECH_CLOSEBROWSER: true,
  SCRIPTING_TXT_EOL: '\n',
  SCRIPTING_XLSX_EOL_SPLIT: '\r',
  SCRIPTING_XLSX_EOL_WRITE: '\r\n',
  SCRIPTING_XLSX_STARTROW: 2,
  SCRIPTING_XLSX_STARTCOL: 1,
  SCRIPTING_NORMALIZE_TEXT: false,
  SCRIPTING_ENABLE_MEMORY: false,
  SCRIPTING_MATCHING_MODE: 'includeLowerCase',
  SCRIPTING_UTTEXPANSION_MODE: 'all',
  SCRIPTING_UTTEXPANSION_RANDOM_COUNT: 1,
  SCRIPTING_MEMORYEXPANSION_KEEP_ORIG: false,
  RETRY_USERSAYS_ONERROR_REGEXP: [],
  RETRY_USERSAYS_NUMRETRIES: 1,
  RETRY_USERSAYS_FACTOR: 1,
  RETRY_USERSAYS_MINTIMEOUT: 1000,
  ASSERTERS:
   [ { ref: 'HASLINK',
       src: 'botium-asserter-basiclink',
       global: false,
       args: null } ],
  LOGIC_HOOKS: [],
  USER_INPUTS: [],
  CONTAINERMODE: 'webdriverio',
  WEBDRIVERIO_URL: 'https://chat.t-mobile.cz/chat/',
  WEBDRIVERIO_PROFILE: '',
  WEBDRIVERIO_INPUT_ELEMENT: '<input />',
  WEBDRIVERIO_INPUT_ELEMENT_VISIBLE_TIMEOUT: 10000,
  WEBDRIVERIO_OUTPUT_ELEMENT:
   "//div[@class='gaid-text-message gaid-text-message--isBot'][position()=last()-1]//p",
  WEBDRIVERIO_IGNOREUPFRONTMESSAGES: false,
  WEBDRIVERIO_USERNAME: '',
  WEBDRIVERIO_PASSWORD: '',
  WEBDRIVERIO_SCREENSHOTS: 'onstop',
  FBPAGERECEIVER_REDISURL: { port: '6379', host: 'redis', db: 0, options: {} },
  WEBDRIVERIO_OPTIONS:
   { desiredCapabilities: { browserName: 'chrome', name: 'TM new - Test Session' },
     protocol: 'http',
     host: '192.168.99.100',
     port: '4444',
     path: '/wd/hub' } }

2019-05-31T08:31:14.636Z: 2019-05-31T08:31:13.519Z botium-BotDriver Build - Sources : { LOCALPATH: '.',
  GITPATH: 'git',
  GITBRANCH: 'master',
  GITDIR: '.' }

2019-05-31T08:31:14.671Z: 2019-05-31T08:31:13.524Z botium-BotDriver Build - Envs : { IS_BOTIUM_CONTAINER: true }

2019-05-31T08:31:14.704Z: 2019-05-31T08:31:13.592Z botium-PluginConnectorContainer Invalid Botium plugin loaded from webdriverio, expected PluginVersion, PluginClass fields

2019-05-31T08:31:14.732Z: 2019-05-31T08:31:13.595Z botium-PluginConnectorContainer Botium plugin botium-connector-webdriverio loaded

2019-05-31T08:31:14.769Z: 2019-05-31T08:31:13.597Z botium-connector-webdriverio Validate called

2019-05-31T08:31:14.801Z: 2019-05-31T08:31:13.600Z botium-connector-webdriverio Build called

2019-05-31T08:31:14.837Z: 2019-05-31T08:31:13.603Z botium-connector-webdriverio Start called

2019-05-31T08:31:24.389Z: 2019-05-31T08:31:24.371Z botium-box-worker sending heartbeat ...

2019-05-31T08:36:24.471Z: 2019-05-31T08:36:24.420Z botium-box-worker sending heartbeat ...

2019-05-31T08:37:15.925Z: 2019-05-31T08:37:15.880Z botium-box-worker-runtestcases Test Session Run failed (Error: ESOCKETTIMEDOUT), doing additional BotDriver Clean.

2019-05-31T08:37:15.961Z: 2019-05-31T08:37:15.881Z botium-connector-webdriverio Clean called

2019-05-31T08:40:02.054Z: 2019-05-31T08:40:02.006Z botium-BaseContainer Cleanup rimrafing temp dir /app/agent/botiumwork/TM-new-Test-Session-20190531-083113-vI4Bx

2019-05-31T08:40:02.357Z: Job failed: Error: ESOCKETTIMEDOUT

Selenium hub log:

08:06:36.629 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
08:06:36.849 INFO [GridLauncherV3.lambda$buildLaunchers$5] - Launching Selenium Grid hub on port 4444
2019-05-31 08:06:37.333:INFO::main: Logging initialized @1175ms to org.seleniumhq.jetty9.util.log.StdErrLog
08:06:38.033 INFO [Hub.start] - Selenium Grid hub is up and running
08:06:38.040 INFO [Hub.start] - Nodes should register to http://172.19.0.4:4444/grid/register/
08:06:38.040 INFO [Hub.start] - Clients should connect to http://172.19.0.4:4444/wd/hub
08:06:40.894 INFO [DefaultGridRegistry.add] - Registered a node http://172.19.0.3:5555
08:06:40.907 INFO [DefaultGridRegistry.add] - Registered a node http://172.19.0.2:5555
08:07:47.391 INFO [RequestHandler.process] - Got a request to create a new session: Capabilities {browserName: firefox, handlesAlerts: true, javascriptEnabled: true, locationContextEnabled: true, loggingPrefs: org.openqa.selenium.logging..., name: TM new - Test Session, requestOrigins: {name: webdriverio, url: http://webdriver.io, version: 4.14.4}, rotatable: true}
08:07:47.409 INFO [TestSlot.getNewSession] - Trying to create a new session on test slot {server:CONFIG_UUID=ad8a2987-e350-456e-b9cf-25ac008d5255, seleniumProtocol=WebDriver, browserName=firefox, maxInstances=1, moz:firefoxOptions={log={level=info}}, platformName=LINUX, version=67.0, applicationName=, platform=LINUX}
08:13:58.927 INFO [RequestHandler.process] - Got a request to create a new session: Capabilities {browserName: chrome, handlesAlerts: true, javascriptEnabled: true, locationContextEnabled: true, loggingPrefs: org.openqa.selenium.logging..., name: TM new - Test Session, requestOrigins: {name: webdriverio, url: http://webdriver.io, version: 4.14.4}, rotatable: true}
08:13:58.935 INFO [TestSlot.getNewSession] - Trying to create a new session on test slot {server:CONFIG_UUID=3f83f707-e0ad-406f-9081-bc7185515bdf, seleniumProtocol=WebDriver, browserName=chrome, maxInstances=1, platformName=LINUX, version=74.0.3729.169, applicationName=, platform=LINUX}
08:31:13.686 INFO [RequestHandler.process] - Got a request to create a new session: Capabilities {browserName: chrome, handlesAlerts: true, javascriptEnabled: true, locationContextEnabled: true, loggingPrefs: org.openqa.selenium.logging..., name: TM new - Test Session, requestOrigins: {name: webdriverio, url: http://webdriver.io, version: 4.14.4}, rotatable: true}
08:31:13.697 INFO [TestSlot.getNewSession] - Trying to create a new session on test slot {server:CONFIG_UUID=3f83f707-e0ad-406f-9081-bc7185515bdf, seleniumProtocol=WebDriver, browserName=chrome, maxInstances=1, platformName=LINUX, version=74.0.3729.169, applicationName=, platform=LINUX}
08:39:59.952 WARN [RequestHandler.process] - The client is gone for session ext. key b54b779b8d4cb90133cf3386ca7ef664, terminating
08:40:02.245 INFO [RequestHandler.process] - Got a request to create a new session: Capabilities {browserName: firefox, handlesAlerts: true, javascriptEnabled: true, locationContextEnabled: true, loggingPrefs: org.openqa.selenium.logging..., name: TM new - Test Session, requestOrigins: {name: webdriverio, url: http://webdriver.io, version: 4.14.4}, rotatable: true}
08:40:02.251 INFO [TestSlot.getNewSession] - Trying to create a new session on test slot {server:CONFIG_UUID=ad8a2987-e350-456e-b9cf-25ac008d5255, seleniumProtocol=WebDriver, browserName=firefox, maxInstances=1, moz:firefoxOptions={log={level=info}}, platformName=LINUX, version=67.0, applicationName=, platform=LINUX}
IP & PORTS
You can access this container using the following IP address and port:

DOCKER PORT     ACCESS URL

jeudi 30 mai 2019

test spring validator organization

I Have a Controller with a request with the annotation @Valid. There are many field to validate so i realize many validator. Also custom validators. How i can organize the validation tests?

I begin with testing NotNull valid.

The Request is same this. and the nested object have Validation field inside also.

@DependsByParam public class ProductionRequestResource extends ProcedureResource implements Serializable { private static final long serialVersionUID = -5759970962934525996L;

private String operatorFiscalCode;

@NotNull(message = "{validation.notNull}")
@Size(min = Ssce2BoConst.NUN_LENGTH, max = Ssce2BoConst.NUN_LENGTH, message = "{validation.size}")
private String nun;

/**
 * Il codice Belfiore del comune.
 */
@Size(min = 4, max = 4, message = "{validation.size}")
private String issuerMunicipalityCode;

@Size(min = 6, max = 6, message = "{validation.size}")
private String issuerIstatCode;

@NotNull(message = "{validation.notNull}")
@DateConstraint(message = "{validation.invalidDate}")
private String issueDate;

@NotNull(message = "{validation.notNull}")
@DateConstraint(message = "{validation.invalidDate}")
private String expiryDate;

@NotNull(message = "{validation.notNull}")
@Size(min = Ssce2BoConst.HALF_PIN_LENGTH, max = Ssce2BoConst.HALF_PIN_LENGTH, message = "{validation.size}")
private String halfPIN;

@NotNull(message = "{validation.notNull}")
@Size(min = Ssce2BoConst.HALF_PUK_LENGTH, max = Ssce2BoConst.HALF_PUK_LENGTH, message = "{validation.size}")
private String halfPUK;

@NotNull(message = "{validation.notNull}")
@Valid
private PrintedDataResource printedData;

@NotNull(message = "{validation.notNull}")
@Valid
private HolderDataResource holderData;


@NotNull
private String issuerName;

private boolean expatriation = false;

private boolean bilingual = false;

@Valid
private BiometricDataResource biometricData;

@Valid
private ShippingDataResource shippingData;

@JsonIgnore
@AssertTrue(message = "{validation.isNotValidRange}")
public boolean isCheckRange() {
    if (expiryDate != null && issueDate != null) {
        return expiryDate.compareTo(issueDate) >= 0;
    }
    return false;
}

public String getOperatorFiscalCode() {
    return operatorFiscalCode;
}

public ProductionRequestResource setOperatorFiscalCode(String operatorFiscalCode) {
    this.operatorFiscalCode = operatorFiscalCode;
    return this;
}

public String getNun() {
    return nun;
}

public ProductionRequestResource setNun(String nun) {
    this.nun = nun;
    return this;
}

/**
 * Il codice Belfiore del comune.
 */
public String getIssuerMunicipalityCode() {
    return issuerMunicipalityCode;
}

public ProductionRequestResource setIssuerMunicipalityCode(String issuerMunicipalityCode) {
    this.issuerMunicipalityCode = issuerMunicipalityCode;
    return this;
}

public String getIssuerIstatCode() {
    return issuerIstatCode;
}

public ProductionRequestResource setIssuerIstatCode(String issuerIstatCode) {
    this.issuerIstatCode = issuerIstatCode;
    return this;
}

public String getIssuerName() {
    return issuerName;
}

public ProductionRequestResource setIssuerName(String issuerName) {
    this.issuerName = issuerName;
    return this;
}

public String getIssueDate() {
    return issueDate;
}

public ProductionRequestResource setIssueDate(String issueDate) {
    this.issueDate = issueDate;
    return this;
}

public String getExpiryDate() {
    return expiryDate;
}

public ProductionRequestResource setExpiryDate(String expiryDate) {
    this.expiryDate = expiryDate;
    return this;
}

public String getHalfPIN() {
    return halfPIN;
}

public ProductionRequestResource setHalfPIN(String halfPIN) {
    this.halfPIN = halfPIN;
    return this;
}

public String getHalfPUK() {
    return halfPUK;
}

public ProductionRequestResource setHalfPUK(String halfPUK) {
    this.halfPUK = halfPUK;
    return this;
}

public boolean isExpatriation() {
    return expatriation;
}

public ProductionRequestResource setExpatriation(boolean expatriation) {
    this.expatriation = expatriation;
    return this;
}

public boolean isBilingual() {
    return bilingual;
}

public ProductionRequestResource setBilingual(boolean bilingual) {
    this.bilingual = bilingual;
    return this;
}

public PrintedDataResource getPrintedData() {
    return printedData;
}

public ProductionRequestResource setPrintedData(PrintedDataResource printedData) {
    this.printedData = printedData;
    return this;
}

public HolderDataResource getHolderData() {
    return holderData;
}

public ProductionRequestResource setHolderData(HolderDataResource holderData) {
    this.holderData = holderData;
    return this;
}

public BiometricDataResource getBiometricData() {
    return biometricData;
}

public ProductionRequestResource setBiometricData(BiometricDataResource biometricData) {
    this.biometricData = biometricData;
    return this;
}

public ShippingDataResource getShippingData() {
    return shippingData;
}

public ProductionRequestResource setShippingData(ShippingDataResource shippingData) {
    this.shippingData = shippingData;
    return this;
}

public static PrintedDataResource newPrintedData() {
    return new PrintedDataResource();
}

public static HolderDataResource newHolderData() {
    return new HolderDataResource();
}

public static BiometricDataResource newBiometricData() {
    return new BiometricDataResource();
}

public static ShippingDataResource newShippingData() {
    return new ShippingDataResource();
}

public static ItalianShipmentResource newItalianShipment() {
    return new ItalianShipmentResource();
}

public static ForeignShipmentResource newForeignShipment() {
    return new ForeignShipmentResource();
}

public static ItalianShipmentDataResource newItalianShipmentData() {
    return new ItalianShipmentDataResource();
}

public static ForeignShipmentDataResource newForeignShipmentData() {
    return new ForeignShipmentDataResource();
}

public static FingerprintsResource newFingerprints() {
    return new FingerprintsResource();
}

public static SignatureResource newSignature() {
    return new SignatureResource();
}

}

I want organize tests in rational mode.

how to write a test case to the follow component.ts code

the test cases written for the above piece of code should increase the code coverage in sonar

if (this.listOfSortJobs.length == 1) {

  sessionStorage.setItem('selectedSortJob', this.listOfSortJobs[0].name);
  this.processflows = this.listOfSortJobs[0].ProcessFlows;
  sessionStorage.setItem('processflow', JSON.stringify(this.processflows));
  this.route.navigate(['/processflow']);
}

the code coverage is not recognising any tests cases written for these

Sharing elements between generated objects in ScalaCheck using nested forAll

Started coding in Scala fairly recently and I tried to write some property based test-cases. Here, I am trying to generate raw data which mimics the system I am testing. The goal is to first generate base elements (ctrl and idz), then use those values to generate two classes (A1 and B1) and finally check their properties. I first tried the following -

import org.scalatest._
import prop._
import scala.collection.immutable._
import org.scalacheck.{Gen, Arbitrary}

case class A(
    controller: String,
    id: Double,
    x: Double
)

case class B(
    controller: String,
    id: Double,
    y: Double
)

object BaseGenerators {
    val ctrl = Gen.const("ABC")
    val idz = Arbitrary.arbitrary[Double]
}

trait Generators {
    val obj = BaseGenerators

    val A1 = for {
        controller <- obj.ctrl
        id <- obj.idz
        x <- Arbitrary.arbitrary[Double]
    } yield A(controller, id, x)

    val B1 = for {
        controller <- obj.ctrl
        id <- obj.idz
        y <- Arbitrary.arbitrary[Double]
    } yield B(controller, id, y)

}

class Something extends PropSpec with PropertyChecks with Matchers with Generators{

    property("Controllers are equal") {
        forAll(A1, B1) {
            (a:A,b:B) => 
                a.controller should be (b.controller)
        }
    }

    property("IDs are equal") {
        forAll(A1, B1) {
            (a:A,b:B) => 
                a.id should be (b.id)
        }
    }

}

Running sbt test in terminal gave me the following -

[info] Something:
[info] - Controllers are equal
[info] - IDs are equal *** FAILED ***
[info]   TestFailedException was thrown during property evaluation.
[info]     Message: 1.1794559135007427E-271 was not equal to 7.871712821709093E212
[info]     Location: (testnew.scala:52)
[info]     Occurred when passed generated values (
[info]       arg0 = A(ABC,1.1794559135007427E-271,-1.6982696700585273E-23),
[info]       arg1 = B(ABC,7.871712821709093E212,-8.820696498155311E234)
[info]     )

Now it's easy to see why the second property failed. Because every time I yield A1 and B1 I'm yielding a different value for id and not for ctrl because it is a constant. The following is my second approach wherein, I create nested for-yield to try and accomplish my goal -

case class Popo(
    controller: String,
    id: Double,
    someA: Gen[A],
    someB: Gen[B]
)

trait Generators {
    val obj = for {
        ctrl <- Gen.alphaStr
        idz <- Arbitrary.arbitrary[Double]
        val someA = for {
            x <- Arbitrary.arbitrary[Double]
        } yield A(ctrl, idz, someA)
        val someB = for {
            y <- Arbitrary.arbitrary[Double]
        } yield B(ctrl, idz, y)
    } yield Popo(ctrl, idz, x, someB)
}

class Something extends PropSpec with PropertyChecks with Matchers with Generators{

    property("Controllers are equal") {
        forAll(obj) {
            (x: Popo) => 
            forAll(x.someA, x.someB) {
                (a:A,b:B) => 
                    a.controller should be (b.controller)
            }
        }
    }

    property("IDs are equal") {
        forAll(obj) {
            (x: Popo) =>
            forAll(x.someA, x.someB) {
                (a:A,b:B) => 
                    a.id should be (b.id)
            }
        }
    }
}

Running sbt test in the second approach tells me that all tests pass.

[info] Something:
[info] - Controllers are equal
[info] - IDs are equal
[info] ScalaTest
[info] Run completed in 335 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.

Is there a better/alternative way to reproduce my desired results? Nesting forAll seems rather clunky to me. If I were to have R -> S -> ... V -> W in my dependency graph for objects sharing elements then I'll have to create as many nested forAll.

How to make a "type" command go >nul if "The system cannot find the file specifed"

So i have a testing batch file that i use to see if my ideas work in batch. i had an idea to make a logging system, but if the file cant be found it doesnt show "The system cannot find the file specified."

ive tried type A6Test.log &if %ERRORCODE%==1 >nul and type A6Test.log ^&if %ERRORCODE%==1 >nul but the first just exited the file and the second displayed

The system cannot find the file specified.
Error occurred while processing: A6Test.log.
The system cannot find the file specified.
Error occurred while processing: &If.
The system cannot find the file specified.
Error occurred while processing: 1.

all you need to recreate this is below.

@echo off
:A6
cls
echo Log file:
type "A6Test.log" ::Problem
set /p Log=
echo %Log%>>"A6Test.log" ::this echos %log% into the log file, "A6Test.log"
goto A6

I expected type "A6Test.log" ^&if %ERRORCODE%==1 >nul to display nothing if the file didnt exist but it showed

Error occurred while processing: A6Test.log.
The system cannot find the file specified.
Error occurred while processing: &If.
The system cannot find the file specified.
Error occurred while processing: 1.```

How to test multiple objects with same method in 1 test class?

I have 2 different objects: C c and B b. B and C implement interface A so that they can use method called color() that is present in interface A. I already made unit test for class B that test the color() method that B has implemented. So what I want to do now is test the color() method in class C with the same unit test of class B. Thus I want to test both of them in the same test class that I have made for class B.

To achieve this, one of my friends said that I would have to make use of the parallel class hierarchy of those classes. But I don't really know how I should implement that in my test.

This is what I have in terms of code:

private static Sprites sprites;
private static B b;

@BeforeAll
static void setUp() {
    sprites = mock(Sprites.class);
    b = new B(sprites);
}

@Test
void testing_color_method() {

    M m = mock(M.class);

    b.color(m);

    verify(sprites).getSpritesOf(m);

}

//... some more tests

I am using JUnit 5 and I know I could use @ParameterizedTest to inject objects B and C in the test to let them use the same unit tests, I have also done some google search about this but none of the search results had it about this kinds of cases where 2 objects need to be injected in the 1 test. So how should I refactor the code so that I can inject class B and C to let them use the same unit tests that I already crated for B?

End to End testing for ReactJS application

I am planning to implement end to end testing in my ReactJS application, I have come across some of the posts mentioning Cypress, but not sure if it's the best and reliable option to use

I have used protractor for Angular

R: test on multiple versions

Does anyone have a solution for automating unit testing of R packages under various multiple versions of R and/or prerequisite packages?

Python has a nice package, tox, which allows the user to write a configuration file specifying what dimensions to expand over, then it runs testing under all combinations of those.

How to speed up the integration test? Each test takes more than 3min

I'm using BDD to do the development. I was a Ruby On Rails developer and am new to Java/Spring.

However, I found the compiled language world is a huge pain during development.

For example, Let's say you're updating your test case.

and run ./gradlew hellowworld:integrationTest --tests="TestA"

Which will take 3 min to run after you done small changes

For example, response.statusCode(201) to response.statusCode(200)

I found the most time-consuming part is booting the server and setup the context every time. However, when you're updating the test case, how come you need to reboot all of your services (Spring/Java is dumb in this way)

I'd like to know is there any way to do the speed up the test?

Hot reloaded?

enter image description here

Jest/Enzyme - TypeError: div.find is not a function

Below is a a little test file that I made for a React project that is using both Jest and Enzyme for testing. In this test, I'm simply trying to find an element in the component and see that it exists (as a truthy conditional). The whole point of this test wasn't just to see if the element existed, but I figured I'd start here. I'm very new to testing, so this syntax/implementation may be bonkers:

import React from 'react';
import ReactDOM from 'react-dom';

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import HamburgerIcon from './HamburgerIcon';

Enzyme.configure({ adapter: new Adapter() });

test('my first test -- will add better text here later', () => {
  const div = document.createElement('div');
  ReactDOM.render(<HamburgerIcon />, div);

  expect(div.find('.closed').exists()).toBeTruthy();

  ReactDOM.unmountComponentAtNode(div);
});

Running this results in this error:

TypeError: div.find is not a function

I originally built this test after seeing this Stack Overflow answer.

I'm not sure how to troubleshoot this, but I'm guessing that maybe I haven't properly "mounted" the component in this test? In the same Stack Overflow thread from the previous link, this answer shows how you would mount a component, but another comment on that answer says that another package needs to be installed in order to do that.

I sort of figured that using the div variable as the container to be searched with find would work, but am I wrong in thinking that?

How to Browser test a Vue.js app mocking API calls?

I have an app that uses Vue.js as Frontend and Spring-boot as Backend.

I want to "unit test" (or integration test, whatever you wanna call it) my views, using browser and selenium, but mocking API calls (ajax requests).

Wich tools are recomended to do that?

PHPUnit mock a class method to return certain value after api call

I'm writing a test in Laravel 5.8 to check some database records get created and relationships exists etc, after an api call is made.

The api call runs a method on a class that makes its own api call to an external service that is needed in the real world but I don't care about it in the test.

I want to mock that class / method so it returns a certain value so that I can forget about it in the test.

Here is my test below, I have attempted to mock the PayPointAdapter class and specifically the makePayment method.

/** @test */
    public function client_can_make_a_payment()
    {
        $client = factory(Client::class)->create();
        $invoice = factory(Invoice::class)->create([
            'client_id' => $client->id
        ]);
        $card = factory(PaymentCard::class)->make([
            'client_id' => $client->id
        ]);

        $this->assertCount(0, $client->payments);
        $this->assertCount(0, $client->paymentCards);

        $mock = \Mockery::Mock(PayPointAdapter::class)
            ->allows(['makePayment' => ["status" => "success", "transid" => 123]]);

        $response = $this->json(
            'POST',
            '/api/payments',
            [
                'invoiceid'                 => $invoice->id,
                'amount'                    => $invoice->total(),
                'clientdetails-firstname'   => $client->first_name,
                'clientdetails-lastname'    => $client->last_name,
                'clientdetails-email'       => $client->email,
                'clientdetails-address1'    => $client->address_line_one,
                'clientdetails-address2'    => $client->address_line_two,
                'clientdetails-city'        => $client->city,
                'clientdetails-state'       => $client->state,
                'clientdetails-postcode'    => $client->postcode,
                'clientdetails-phonenumber' => '',

                'cardtype'     => $card->type,
                'cardnum'      => $card->number,
                'cardexp'      => $card->expiry,
                'cardstart'    => $card->start,
                'cardissuenum' => $card->issue,
                'cccvv'        => $card->ccv
            ]
        );

        $response->assertStatus(201);
        $client->refresh();
        $invoice->refresh();
        $this->assertCount(1, $client->paymemnts);
        $this->assertCount(1, $client->paymentCards);
        $this->assertDatabaseHas('payment_cards', $card->toArray());
        $this->assertTrue($invoice->isPaid());
    }

Here is the method in the controller that handles the api call

/**
     * Make a payment.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    public function store(Request $request)
    {
        try {
            $payment = $this->payPointAdapter->makePayment($request->all());

            $card = PaymentCard::where('type', request('cardtype'))
                ->where('expiry', request('cardexp'))
                ->where('start', request('cardstart'))
                ->where('ccv', request('cccvv'))
                ->get()
                ->filter(function ($paymentCard) {
                    return $paymentCard->number == request('cardnum');
                });

            if (!$card) {
                $card = PaymentCard::create([
                    'number' => request('cardnum'),
                    'type'   => request('cardtype'),
                    'expiry' => request('cardexp'),
                    'start'  => request('cardstart'),
                    'issue'  => request('cardissuenum')
                ]);
            }

            Payment::create([
                'invoice_id'      => request('invoiceid'),
                'amount'          => request('amount'),
                'payment_method'  => request('payment_method'),
                'payment_card_id' => $card->id,
                'reference'       => $payment['transid']
            ]);

            return response($payment, 201);
        } catch (\Exception $ex) {
            return response($ex->getMessage(), 500);
        }
    }

So I simply want to ignore the call to method $this->payPointAdapter->makePayment($request->all()); and get the test to mock the response to that.

In my test the mock I created doesn't stop it running the method. Any ideas?

AssertJ: make assertion that all Assert objects were asserted upon

When using the AssertJ library, I'm interested in being able to assert that all org.assertj.core.api.Assert objects had an actual assertion made on them. That is, a test such as the following should fail because it is clearly a mistake:

import static org.assertj.core.api.Assertions.assertThat;

// ... elided ...

@Test
public void unfinishedAssertion() {
    assertThat("str");
}

Is there a way to configure this with AssertJ, or to make this assertion in a JUnit @After method?

My only thought is to provide a static factory like assertThat that returns a proxy, delegating all method invocations to the underlying Assert, and using an After method to assert that the proxy had at least one invocation with a method that was not Assert#as or Assert#withFailMessage, etc., but this seems cumbersome and unnecessary as the library should provide this functionality itself.

MVC Policy Override in Integration Tests

I am in the process of adding integration tests at work for an MVC app. Many of our endpoints have policies applied to them, e.g.

namespace WorkProject
{
  [Route("A/Route")]
  public class WorkController : Controller
  {
    [HttpPost("DoStuff")]
    [Authorize(Policy = "CanDoStuff")]
    public IActionResult DoStuff(){/* */}
  }
}

For our integration tests, I have overridden the WebApplicationFactory like it is suggested in the ASP .NET Core documentation. My goal was to overload the authentication step and to bypass the policy by making a class which allows all parties through the authorization policy.

namespace WorkApp.Tests
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup: class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);
            builder.ConfigureServices(services =>
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Test Scheme"; // has to match scheme in TestAuthenticationExtensions
                    options.DefaultChallengeScheme = "Test Scheme";
                }).AddTestAuth(o => { });


                services.AddAuthorization(options =>
                {
                    options.AddPolicy("CanDoStuff", policy =>
                        policy.Requirements.Add(new CanDoStuffRequirement()));
                });

             // I've also tried the line below, but neither worked
             // I figured that maybe the services in Startup were added before these
             // and that a replacement was necessary
             // services.AddTransient<IAuthorizationHandler, CanDoStuffActionHandler>();
             services.Replace(ServiceDescriptor.Transient<IAuthorizationHandler, CanDoStuffActionHandler>());
            });
        }
    }

    internal class CanDoStuffActionHandler : AuthorizationHandler<CanDoStuffActionRequirement>
    {
        public CanDoStuffActionHandler()
        {
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CanDoStuffActionRequirement requirement)
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }

    internal class CanDoStuffRequirement : IAuthorizationRequirement
    {
    }
}

The first thing that I do to the services is override the authentication as suggested here (without the bit about overriding Startup since that didn't seem to work for me). I am inclined to believe that this authentication override works. When I run my tests, I receive an HTTP 403 from within the xUnit testing framework. If I hit the route that I am testing from PostMan I receive an HTTP 401. I have also made a class that lives in the custom web application factory that allows all requests for the CanDoStuff authorization handler. I thought this would allow the integration tests through the authorization policy, but, as stated above, I receive an HTTP 403. I know that a 403 will be returned if the app doesn't know where certain files are. However, this is a post route strictly for receiving and processing data and this route does not attempt to return any views so this 403 is most likely related to the authorization policy which, for some reason, is not being overridden.

I'm clearly doing something wrong. When I run the test under debug mode and set a breakpoint in the HandleRequirementsAsync function, the application never breaks. Is there a different way that I should be attempting to override the authorization policies?

Problems when accessing Session attributes in Spring Test

I am developing a Spring webservice and I need to read data & set them as a Session attribute in an interceptor. Everything works fine when I test the endpoints using an external client. However, I get a NullPointerException when I try the code below:

@RunWith(SpringRunner.class)
@WebMvcTest(AccountController.class)
public class AccountControllerTest {

private MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@MockBean
private IncomingInterceptor incomingInterceptor;

@MockBean
private AccountService accountService;

@MockBean
private FileStoreService fileStoreService;

@MockBean
private HttpServletRequest request;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws Exception {
    JsonObject root = new JsonObject();
    root.add("body", gson.toJsonTree(account));

    Mockito.when(accountController.addAccount()).thenReturn(new ResponseEntity<>(1L, HttpStatus.OK));

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/account/register")
            .content(root.toString())
            .characterEncoding("utf-8")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();

    String contentAsString = mvcResult.getResponse().getContentAsString();
    System.out.println("contentAsString = " + contentAsString);
}
}

Everyting works as expected when the attributes are set in the interceptor but when I try to access them in AccountController an exception is thrown.

The code to access attributes:

 JsonObject body = (JsonObject) request.getSession().getAttribute("body");           

Thanks in advance!

How to test a data retrieval module?

I am working on a project and have a data retrieval module written on python. All it does is build a query using string manipulations and then executes the query using another module (a connection module). I want to make unit tests properly. Does anyone have any recommendations on techniques? Is mocking a proper way to do so?

JUNIT: create tests based on how many files are in a folder

Goodmorning everyone, I wanted to know if it was possible with the path of a folder containing json files to run them regardless of how many they are.

if I have 3 json files it will do 3 tests. if 4, 4 tests.

Thank you

Check if native FileReader is trigerred after input click

I am trying to write a test based on this anwer: How can I test a change handler for a file-type input in React using Jest/Enzyme?

 it('checks if native file reader is triggered', () => {
    const componentWrapper = mountWithIntl(<UploadFileButton   {...fakeProps} />);
    const fileContents = 'file contents';
    const readAsText = jest.fn();
    const addEventListener = jest.fn((_, evtHandler) => {
      evtHandler();
    });
    const dummyFileReader = {
    addEventListener,
    readAsText,
    result: fileContents,
    };
    window.FileReader = jest.fn(() => dummyFileReader);
    componentWrapper.find('input').simulate('click');
    expect(FileReader).toHaveBeenCalled();
  });

I get an error:

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.

mercredi 29 mai 2019

Should we modify a function signature for unit testing?

Suppose I have a function add() as below:

void add(int a, int b) {
    int sum=a+b;
    cout<<sum;
    sendSumToStorage(sum);
}

This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file). This is how we ideally want it in the application (meaning, we don't want it to return anything).

For purposes of unit testing, is it valid (from a design perspective) if I modify the function signature so that it returns the sum? I could then have a test like:

bool checkAdd() {
    in res=add(3, 4);
    if(res==7) return true;
    else return false;
}

Better yet, is this (returning a value) the only way we could unit test it? Is there some valid way in which we could unit test the add() function without changing the function signature?

Which is the correct code structure to be followed for getting the best output using TestModules in Canoe?

I am using CANoe 10.0 to do some Diagnostic testing and I have to generate reports for the tests. So, I am using Test Setup to create my test cases using CAPL. I know that the test starts from the function "MainTest". After this, I don't know how to structure my test case and which functions to use to get the correct format in the report. For example, I want to send a Diagnostic request and expecting a particular response. I want to be able to show in the report, the sending of the message, what response was received and what response was expected. Based on this, the verdict should be displayed.

travis CI build replication on Windows machine

A recent Travis build of the open source geopandas project makes use of a YAML file to set up the remote environment on the build machine. It seems that the build is done on a non-Windows machine (unsure if it is Linux or Ubuntu), but it seems to set up the environment with no issues.

I tried to set up an identical environment with the purposes of running the test suite locally. I executed the following command in my anaconda prompt:

conda env create --file D:\github_projects\geopandas\ci\travis\35-minimal.yaml --name geopandas-dev-python3

Unfortunately this raises an error:

Collecting package metadata: done
Solving environment: failed

UnsatisfiableError: The following specifications were found to be in conflict:
  - fiona=1.7
  - numpy=1.12
  - python=3.5
  - shapely=1.5
Use "conda search <package> --info" to see the dependencies for each package.

This is a bit confusing to me since I was under the impression that python dependencies as implemented by Anaconda are platform-independent. Is this assumption wrong? If not then why am I getting this error on my local Windows machine, while the remote non-Windows machine seems to be setting up the environment with no issues?

How do I stub a function that is not directly passed to the calling function?

I have an express app with API endpoints secured using JWT token. I have a method that verifies a received token.

// authentication.js

import jwt from 'jsonwebtoken';
import Settings from '../settings';

const AuthenticationMiddleware = {
    verifyToken: (req, res, next) => {
        const token = req.headers['x-access-token'];
        if (!token) {
            const msg = 'Include a valid token in the x-access-token header';
            return res.status(422).json({ 
                error: 'No token provided',
                msg 
            });
        }
        try {
            req.user = jwt.verify(token, Settings.jwtSecret);
            req.token = token;
            return next();
        }
        catch (e) {
            return res.status(422).json({ error: 'Invalid token' });
        }
    }
};

export default AuthenticationMiddleware;

This works fine when I call the API endpoints from postman with the token header included.

Now I have a test such as shown below. There's about 40 of them, each requiring a token to be sent with each API request.

// should is not used directly in the file but is added as a mocha requirement

import supertest from 'supertest';
import app from '../app';

const server = supertest.agent(app);
const BASE_URL = '/api/v1';

describe('/loans: Get all loans', () => {
    it('should return a list of all loans', done => {
        server
            .get(`${BASE_URL}/loans`)
            .expect(200)
            .end((err, res) => {
                res.status.should.equal(200);
                res.body.data.should.be.an.instanceOf(Array);
                for (const each of res.body.data) {
                    each.should.have.property('id');
                    each.should.have.property('userid');
                }
                done();
            });
    });
});

I've looked at sinon and tried stubbing the verifyToken function in mocha's before hook like so

import sinon from 'sinon';
import AuthenticationMiddleware from '../middleware/authentication';

before(() => {
    const stub = sinon.stub(AuthenticationMiddleware, 'verifyToken');
    stub.returnsThis()
});

But I can already see a problem here. While the verifyToken stub may have been created, it is NOT used during the test. The verifyToken that is being called during the test is passed as middleware from the route like so

router.get('/loans', AuthenticationMiddleware.verifyToken, LoansController.get_all_loans);

I want a way to stub verifyToken during the test so that I can just return next() immediately.

My question is, is it possible to stub AuthenticationMiddleware.verifyToken universally during the test so that all calls to the API endpoint call the stubbed version?

How to test multiple objects with @ParameterizedTest?

So I want to test objects of different classes (all extending to one class called "Entities") in one test case by using @ParameterizedTest. But Somehow it doesn't work for me. What is the solution to this problem?

I have tried the following (which gives me errors).

@ParameterizedTest
@CsvSource({
    "Car",
    "Airplane",
    "Bike"
})
@Test
void testing_multiple_objects(Object obj) {

    Object object = mock(obj.getClass());

    Coloring.colorOf(null, (Entities) object);

    verify(colorNotFound, never());
}

Jest test process never completing after all tests pass. How can I get them to complete

I have a Jest test class with 2 tests that are both passing fine. My problem is that when I run yarn run test my tests execute but Jest hangs. After digging around online I found a lot of people talking about not handling async/await correctly, but based on everything I see in the Jest docs my implementation is correct. I also tried running the tests with the flag --detectOpenHandles but it gives me no information. The last message I get in my console is "Ran all test suites." but it just hangs after that and never closes the test process. If I use the --forceExit flag is closes fine, but I don't want to have to use this. How can I get my tests to complete?

This is my test class:

describe('urlShortener middleware', () => {

  const LONG_URL = "www.google.com";
  const SHORT_URL = "www.g.com";

  let shortenUrl;

  const req = {
    body: {
      url: LONG_URL
    }
  };

  const res = { end: jest.fn(), json: jest.fn(), status: jest.fn().mockReturnThis() };

  const mockResponse = {
    body: {
      "short_url": SHORT_URL
    },
    status: 201  
  };

  let axiosMock = {
    post: jest.fn().mockResolvedValue(mockResponse)
  };

  beforeEach(() => {
    req.body = {url: LONG_URL};

    jest.setMock('axios', axiosMock);
    shortenUrl = require('../urlShortener').default;

    res.end.mockReset();
    res.json.mockReset();
    res.status.mockReset();

    res.status.mockReturnValue(res);
  });

  it('should return the data appropriately when nothing goes wrong', async (done) => {
    await shortenUrl(req, res);

    expect(axiosMock.post.mock.calls[0][1].original_url).toBe(LONG_URL);
    expect(res.status).toHaveBeenCalledTimes(1);
    expect(res.status).toHaveBeenCalledWith(201);
    expect(res.json).toHaveBeenCalledWith({ shortUrl: SHORT_URL });

    done();
  });

  it('should set the correct status when the world burns', async (done) => {
    axiosMock.post = jest.fn().mockRejectedValue(new Error());

    await shortenUrl(req, res);

    expect(res.status).toHaveBeenCalledTimes(1);
    expect(res.status).toHaveBeenCalledWith(500);
    expect(res.json).toHaveBeenCalledTimes(1);

    done();
  });
});

Cannot use attach_mock with an autospec function mock

Library module:

# mod.py
def foo():
    bar1("arg1")
    bar2("arg2x", "arg2y")

def bar1(x):
    pass

def bar2(x, y):
    pass

Test module:

# test_mod.py
from mod import foo

def test_foo(mocker):
    mock = mocker.MagicMock()
    mock.attach_mock(mocker.patch("mod.bar1"), "b1")
    mock.attach_mock(mocker.patch("mod.bar2", autospec=True), "b2")
    foo()
    mock.assert_has_calls(
        [
            mocker.call.b1("arg1"),
            mocker.call.b2("arg2x", "arg2y"),
        ]
    )

The mocker fixture is from pytest-mock plugin. Execute the MCVE with python -m pytest.

This test fails for weird reasons.

E       AssertionError: Calls not found.
E       Expected: [call.b1('arg1'), call.b2('arg2x', 'arg2y')]
E       Actual: [call.b1('arg1')]

Without the autospec it works. Does using autospec break the attach_mock feature? How should the test for foo assert on the order and args of the calls to dependencies bar1 and bar2 without losing their autospec?

How to test Spring REST webservice when using a HandlerInterceptorAdapter?

I am developing a Spring web service. I want to test my endpoints but for some reason I always get the following exception when I run the tests:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....IncomingInterceptor' 

However, I annotated the class with @Component. The interceptor works when I test the endpoint using an external client! Does somebody know how to solve this problem?

Here is my code when I test the endpoint: private MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@Mock
private IncomingInterceptor incomingInterceptor;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws 
    mockMvc.perform(MockMvcRequestBuilders.post("/account/add")
            .content(gson.toJson(account))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNotEmpty());
}

The code for the IncomingInterceptor:

@Component
public class IncomingInterceptor extends HandlerInterceptorAdapter {

@Autowired
private Gson gson;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//code in here works
    return true;
}
}

Note: I do not want to test if the Interceptor works, I want to test the Endpoints!!! Thanks in advance!

Cannot attach mocks with an autospec

# mod.py

def foo():
    bar1("arg1")
    bar2("arg2")

def bar1(x):
    pass

def bar2(x):
    pass

Suppose we want to test foo, asserting that it calls bar1 and bar2 in that order. It's possible like this:

# test_mod.py

from mod import foo

def test_foo(mocker):
    mock = mocker.MagicMock()
    mock.attach_mock(mocker.patch("mod.bar1"), "b1")
    mock.attach_mock(mocker.patch("mod.bar2"), "b2")
    foo()
    mock.assert_has_calls(
        [
            mocker.call.b1("arg1"),
            mocker.call.b2("arg2"),
        ]
    )

The mocker fixture is from pytest-mock plugin. Execute the MCVE with python -m pytest.

It works, however this approach has a big flaw in practice. Should the signature of bar2 change (e.g. it's not defined directly in mod.py but was imported from a third-party dependency), then foo can become completely broken yet the tests can not detect such a change, because that dependency was mocked out in the first place.

If something upstream changed in bar2, for example another argument is added:

def bar2(x, y):
    pass

The tests still pass, but the library code is now broken:

>>> from mod import foo
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    bar2("arg2")
TypeError: bar2() missing 1 required positional argument: 'y'

The usual solution to this issue is to autospec your mocks. An autospec would cause foo() to fail during the test, too, because bar2 is called with incompatible signature.

Updated library:

def foo():
    bar1("arg1")
    bar2("arg2x", "arg2y")

def bar1(x):
    pass

def bar2(x, y):
    pass

Updated test:

from mod import foo

def test_foo(mocker):
    mock = mocker.MagicMock()
    mock.attach_mock(mocker.patch("mod.bar1"), "b1")
    mock.attach_mock(mocker.patch("mod.bar2", autospec=True), "b2")
    foo()
    mock.assert_has_calls(
        [
            mocker.call.b1("arg1"),
            mocker.call.b2("arg2x", "arg2y"),
        ]
    )

These tests now fail for reasons I don't understand.

E       AssertionError: Calls not found.
E       Expected: [call.b1('arg1'), call.b2('arg2x', 'arg2y')]
E       Actual: [call.b1('arg1')]

Why did adding autospec break the attach_mock feature? How should you assert the order of calls without losing autospec?

Send wildcard param in a MockMvc test

Hy everyone, I am working with the sping rest docs libray and I have to send a wildcard param to some mocked method, I'm doing the next:

val contextRequest = RequestBrowsePlayerContext(this.standardContext, this.sWDIContext, this.uIDContext, this.seeAllContext, apiRequest)
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))

But I want to send a wildcard param because I am getting null in the test, due to they are different objects, I know that wuth spock we can do something like:

mockBrowsePlayerProvider.getEntitiesBrowse(_ as BrowsePlayerContext) >> Single.just(buildMockEntitiesBrowse())

And we can use the _ wildcard param. But I don't know how to do that in kotlin.

Any ideas?

Using FsCheck I get different result on tests, once 100% passed and the other time error

I created a generator to generate lists of int with the same lenght and to test the property of zip and unzip. Running the test I get once in a while the error

Error: System.ArgumentException: list2 is 1 element shorter than list1

but it shouldn't happen because of my generator.

I got three times the test 100% passed and then the error above. Why? It seems my generator is not working properly.

let samelength (x, y) = 
    List.length x = List.length y

let arbMyGen2 = Arb.filter samelength Arb.from<int list * int list> 

type MyGenZ =
    static member genZip() = 
       {
        new Arbitrary<int list * int list>() with
            override x.Generator = arbMyGen2 |> Arb.toGen
            override x.Shrinker t = Seq.empty
    }

let _ = Arb.register<MyGenZ>()

let pro_zip (xs: int list, ys: int list) = 
   (xs, ys) = List.unzip(List.zip xs ys)
   |> Prop.collect (List.length xs = List.length ys)

do Check.Quick pro_zip

How do i remove a like from a photo in my code

I have written a program for a photo upload site where users can like photos, I have a test script to like the photo then display all the likes then i want to remove the like and display all the likes now. How do i do this?

import java.util.*;

public class Likes {
    private static Hashtable<Photo, TreeSet<User>> likes = new Hashtable<>();

    //like photo
    public static void like(Photo photo, User user) {
        try {
            likes.get(photo).add(user);
        }
        catch (NullPointerException e) {
            likes.put(photo, new TreeSet<>());
            likes.get(photo).add(user);
        }
    }



    //unlike photo
    public static void unlike(Photo photo, User user) {
        try {
            likes.get(photo.remove(user));
        }
        catch (NullPointerException e) {

        }
    }

    //has liked photo
    public boolean hasliked(Photo photo, User user) {
        try {
            return likes.get(photo).contains(user);
        }
        catch (NullPointerException e) {
            return false;
        }
    }

    //get all likes
    public List<Photo> getAllLikes(User user){
        // new empty list
        List<Photo> likedphotos = new ArrayList<Photo>();

        for (Photo photo : likes.keySet()) {
            if(hasliked(photo, user)){
                // add photo to list
                likedphotos.add(photo);
            }
            // return that initial list
        }

        return likedphotos;

    }



    public String toString() {
        return likes.toString();
    }

    public void get(Photo remove) {
    }

    public void remove(Photo photo1, User user1) {
    }
}

Tests:

import java.sql.SQLOutput;
import java.util.*;

public class TestDrive {

    public static void main(String[] args) throws InputValidationException {



        //create 2 photo object
        Photo photo1 = new Photo();
        Photo photo2 = new Photo();

        //create 1 user object
        User user1 = new User();

        //create 1 like object
        Likes likes1 = new Likes();


        //set 2 photos
        photo1.setimageURL("photo of user 2");
        photo2.setimageURL("photo of user 1");

        //print the 2 photos
        System.out.println(photo1.getimageURL());
        System.out.println(photo2.getimageURL());


        //set 1 user
        user1.setUserName("oopnoob");

        //print the username
        System.out.println(user1.getUserName());

        //Like the 2 photos


        Likes.like(photo1, user1);
        Likes.like(photo2, user1);

        //Test the hasliked method to see if user1 has liked both photos - both should return true

        System.out.println("Should be true: " + likes1.hasliked(photo1, user1));
        System.out.println("Should be true: " + likes1.hasliked(photo2, user1));


        //Test the getAllLikes for user1. Should print 2 photos.

        System.out.println("user1 liked: " + likes1.getAllLikes(user1));


//i dont know how to remove the like from the photo

        //Test the unlike feature by unliking photo1

        likes1.unlike(photo1, user1);


        //Test the getAllLikes - should only print one photo

        System.out.println("user1 liked: " + likes1.getAllLikes(user1));







    }

}

Why are there different proportions for different test types?

We have decided in the company to redesign our type of tests, that we have a pyramid shape of 4 types of tests. I have seen that this structure is common and occurs frequently. The structure is as the following (the numbers are estimated so you can imagine the pyramid):

  • GUI tests (5%)
  • API test (10%)
  • Integration test (25%)
  • Unit test (60%)

My question is not directly what kind of tests these are (if someone would like to explain them in 1-2 sentences I would of course be happy), but rather why we try to keep and design them in a pyramid shape? How is this connected and how can this be explained?

Is it due to the speed, the accuracy of the tests and the associated scope? Why do we need different proportions of tests?

I can't explain why we don't have unit tests on the top level. I would be very happy about an answer.

UFT 14.01 unable to recognise chrome objects

Setting up a new regression project on a salesforce web application. UFT is unable to recognise any elements in Chrome and just sees the window as "Chrome Legacy Window"

Chrome Version 74.0.3729.157

Installed both UFT and Microfocus addon Tried drag and drop Agent.cfx from Installations/chomr - giving an CRX invalid error

Neither of these worked.

How to add devices to Device set in Botium Box

I'm setting Botium box Device set, but I can't choose any Devices. I've set my local Selenium Hub in Device providers. My Selenium hub is running in Docker.

I'm trying to follow this guide: https://botium.atlassian.net/wiki/spaces/BOTIUM/pages/32145510/Run+Selenium+Grid+and+Connect+to+Botium+Box

I can't see any devices provided by auto compete, but I can see Firefox and Chrome in Selenium Grid Console.

Cannot read property 'doc' of undefined when mocking service class through spy/karma

I am trying to test my angular application through Karma. My application is connected to a firebase firestore database. I am trying to mock a collection and use this to test my component functions.

The code snippets that I am using are the following:

sprint.service.ts:

export class SprintService {

  getSprints() {
    return this.firestore.collection('sprints').snapshotChanges();
  }
  constructor(private firestore: AngularFirestore) { }
}

sprints.component.ts

sprints : Sprint[];

constructor(private sprintService: SprintService) { }

ngOnInit() {
    this.sprintService.getSprints().subscribe(data => {
      this.sprints = data.map(e => {
        return {
          id: e.payload.doc.id, //HERE IT ERRORS
          ...e.payload.doc.data()
        } as Sprint;
      })
    });
  }

sprints.component.spec.ts

//Mock class
class MockSprintServce
{
  getSprints(){
    return of([
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ])
    }
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, AngularFireModule.initializeApp(environment.firebase) ],
      declarations: [ ArchivedUserstoriesComponent,SprintDetailComponent, SprintsComponent, UserDetailComponent, UsersComponent, UserstoriesComponent, UserstoryDetailComponent ],
      providers: [AngularFirestore, {provide: SprintService, useClass: MockSprintServce}]
    })
    .compileComponents();
  }));

beforeEach(() => {
    app.sprints = [
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ]
  });


it(`should return all Sprints`, async(() => {

    //arrange
    let getSpy = spyOn(mockSprintServiceObject, 'getSprints').and.returnValue({ subscribe: () => {} });

    //act
    app.ngOnInit({});

    //assert
    expect(getSpy).toHaveBeenCalled();
    expect(getSpy).toContain(app.sprints[1]);
  }));

I want the code to be working without any errors. I probably think i have to rewrite the getSprints method in my MockSprintService. Does anybody know what i should return or generate in the getSprints() method to make my ngOnInit work again? Help would be appreciated.

How to fix Boot layer in initialization in selenium webdriver

I'm using selenium webdriver tool for automation testing. In this, I am facing an error whenever I import the safariwebdriver class and Webdriver method. the error sign not resolve.

Error occurred during initialization of boot layer java.lang.module.ResolutionException: Modules selenium.server.standalone and okio export package org.openqa.selenium.safari to module net.bytebuddy

mardi 28 mai 2019

How to test a routing handler calling via mock from express

I'm unit-testing some code of mine in nodejs that works with express. While it seems obvious, I want to test that my routes are calling the right handler functions.

I'm using jest to create a mock function for the handler function. While I successfully tried to test that a function is called inside another function, I cannot seem to test that a function (handler) is called from express get of post. Let's see an examplee:

fruits.js

function orange (req,res,next) {res.status(200)} ;
module.exports = {orange}

app.js

const fruits = require('./fruits')
const express = require('express');
const app = express();

app.get('/fruits', fruits.orange);

module.exports = { app };

When I'm trying to test (with jest) that GET request (with the help of axios module) to /fruits is calling orange(), altough actually orange() works, it won't be saved as a calling with a mock function cover of spy cover.

How can I test that orange() has been called from the GET request ?

Puppeteer - the tests do not perform any action

so, I'm using Puppeteer with Jest. After adding

    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();

My tests does not perform any actions. It doesn't matter if I'm using headless mode or let's call it "normal" mode. Anybody can help me?

homepage.test.js

const puppeteer = require('puppeteer');
const HomePage = require('./page_objects/HomePage');

const homePage = new HomePage();
describe('Homepage', () => {
  beforeAll(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto(homePage.path);
    await page.waitForSelector(homePage.loginPanel);
  });
  it('Log into your account', async () => {
    await homePage.fillLoginForm();
    await expect(page).toMatchElement(homePage.productList);
    await page.screenshot({ path: 'example.png' });
  });

HomePage.js

module.exports = class HomePage {
  constructor() {
    this.path = 'https://www.saucedemo.com/index.html';
    this.loginPanel = '#login_button_container';
    this.productList = 'div[class="inventory_container"]';
    this.loginForm = {
      fields: {
        usernameInput: 'input[id="user-name"]',
        passwordInput: 'input[id="password"]',
        logInButton: 'input[class="btn_action"]',
      },
    };
  }

  async fillLoginForm() {
    await page.type(this.loginForm.fields.usernameInput, 'standard_user');
    await page.type(this.loginForm.fields.passwordInput, 'secret_sauce');
    await page.click(this.loginForm.fields.logInButton);
  }
};


Pass parameters to a get with spring mvc test

I am using spring rest docs to generate the documentation of an API. My problem is that inside the get I have some objects which are created from other ones, so I need to mock these objects with are the base to create others ones. I'm not pretty sure how can I achieve that. This is what I am doing now:

My Controller looks like this:

import com.espn.api.platform.model.*
import com.espn.csemobile.espnapp.context.*
import com.espn.csemobile.espnapp.context.common.RequestBasedSWIDContext
import com.espn.csemobile.espnapp.context.common.RequestBasedSeeAllContext
import com.espn.csemobile.espnapp.context.common.RequestBasedUIDContext
import com.espn.csemobile.espnapp.models.browseplayer.BrowsePlayerResponse
import com.espn.csemobile.espnapp.services.browseplayer.BrowsePlayerServiceRepresentable
import com.espn.csemobile.espnapp.services.browseplayer.contexts.RequestBrowsePlayerContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import rx.Single

@Controller
@ProductApi(
        id = "v1_browse_player",
        title = "Browse Player (v1)",
        description = "")
class BrowsePlayerController(private val transaction: Transaction,private val apiRequest: ApiRequest) {

    @Autowired
    lateinit var browsePlayerService: BrowsePlayerServiceRepresentable

    @GetRequest(
            path = "/v1/browse/players",
            timeToLive = 300,
            queries = [
                QueryParameter(name = "swid", required = true),
                QueryParameter(name = "uid"),
                QueryParameter(name = "seeAll", type = java.lang.Boolean::class),
                QueryParameter(name = "lang", required = true),
                QueryParameter(name = "region", required = true),
                QueryParameter(name = "version", required = true, type = Integer::class),
                QueryParameter(name = "appName", required = true),
                QueryParameter(name = "platform", required = true)
            ]
    )
    @GetMapping()
    fun processBrowsePlayerRequest(transaction: Transaction, apiRequest: ApiRequest): Single<BrowsePlayerResponse?> {
        val applicationContext = RequestBasedApplicationContext(apiRequest)
        val standardContext = RequestBasedStandardContext(
                RequestBasedVersionContext(apiRequest),
                applicationContext,
                RequestBasedEditionContext(apiRequest, applicationContext),
                RequestBasedPlatformContext(apiRequest),
                transaction
        )
        val swidContext = RequestBasedSWIDContext(apiRequest)
        val uidContext = if (checkUIDPresent(apiRequest)) RequestBasedUIDContext(apiRequest) else null
        val seeAllContext = RequestBasedSeeAllContext(apiRequest)
        val requestBrowsePlayerContext = RequestBrowsePlayerContext(standardContext, swidContext, uidContext, seeAllContext, apiRequest)
        return browsePlayerService.getEntitiesBrowse(requestBrowsePlayerContext)
    }

    private fun checkUIDPresent(apiRequest: ApiRequest): Boolean =
            apiRequest.parameters["uid"] != null
}

The issue is for example when I want to create this object: val swidContext = RequestBasedSWIDContext(apiRequest) which depends from the apiRequest one.

My test is just like this:

import com.espn.api.platform.model.ApiRequest
import com.espn.api.platform.model.Transaction
import com.espn.csemobile.espnapp.context.StandardContext
import com.espn.csemobile.espnapp.context.common.SWIDContext
import com.espn.csemobile.espnapp.context.common.SeeAllContext
import com.espn.csemobile.espnapp.context.common.UIDContext
import com.espn.csemobile.espnapp.models.UID
import com.espn.csemobile.espnapp.models.browseplayer.*
import com.espn.csemobile.espnapp.services.browseplayer.BrowsePlayerServiceRepresentable
import com.espn.csemobile.espnapp.services.browseplayer.contexts.RequestBrowsePlayerContext
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.restdocs.JUnitRestDocumentation
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultHandlers.print
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
import rx.Single

@RunWith(SpringRunner::class)
@WebMvcTest(BrowsePlayerController::class, secure = false)
@AutoConfigureRestDocs(outputDir = "target/snippets")
class BrowsePlayerControllerTest {

    @Autowired
    lateinit var mockMvc: MockMvc
    @MockBean
    private lateinit var browsePlayerServiceRepresentable: BrowsePlayerServiceRepresentable
    @MockBean
    private lateinit var standardContext: StandardContext
    @MockBean
    private lateinit var sWDIContext: SWIDContext
    @MockBean
    private lateinit var uIDContext: UIDContext
    @MockBean
    private lateinit var seeAllContext: SeeAllContext
    @MockBean
    private lateinit var apiRequest: ApiRequest
    @Autowired
    lateinit var context: WebApplicationContext
    @MockBean
    private lateinit var transaction: Transaction
    @get:Rule
    var restDocumentation = JUnitRestDocumentation()

    @Before
    fun init() {
        MockitoAnnotations.initMocks(this)
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply<DefaultMockMvcBuilder>(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation)
                        .uris()
                        .withScheme("http")
                        .withHost("localhost")
                        .withPort(8080))
                .build()
    }

    @Test
    @Throws(Exception::class)
    fun shouldReturnDefaultMessage() {
        val paramsMock = mapOf("swid" to "asudyasd-asdasd-asdasd")
        `when`(apiRequest.parameters).thenReturn(paramsMock)
        val contextRequest = RequestBrowsePlayerContext(this.standardContext, this.sWDIContext, this.uIDContext, this.seeAllContext, apiRequest)
        //`when`(RequestBrowsePlayerContext.(MockMvc., sWDIContext, uIDContext, seeAllContext, apiRequest)).thenReturn(contextRequest)
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        this.mockMvc!!.perform(get("/v1/browse/players/{transaction}{apiRequest}",transaction,apiRequest).param("swid", "asudyasd-asdasd-asdasd")
                .param("uid", "s:20~l:23").param("seeAll", true.toString()).param("lang", "es")
                .param("region", "us").param("version", "23").param("appName", "espn")
                .param("platform", "espn"))
                .andDo(print())
    }

    private fun  presentBrowsePlayers(): BrowsePlayerResponse {
        var sections = arrayListOf<Node>()
        val playersResponse = buildMockSuggestedPlayers()
        val nodePlayers =  Node(null, SectionType.PLAYERS, playersResponse)
        sections.add(nodePlayers)
        val entitiesResponse = buildMockEntitiesBrowse()
        val nodeEntities =  Node(null, SectionType.ENTITIES, entitiesResponse)
        sections.add(nodeEntities)
        return  BrowsePlayerResponse(presentTopHeader(), buildAnalytics(), sections)
    }

    private fun buildMockSuggestedPlayers(): List<SuggestedPlayer> {
        val items = arrayListOf<SuggestedPlayer>()
        items.add(SuggestedPlayer(
                "http://i.espncdn.com/i/players/130x180/45843.jpg",
                "Lionel Messi",
                "SOCCER",
                "dc5f8d51332b0ab2b4b0c97efdc624e0",
                buildAnalyticsPlayer("s:600~t:83", "s:600~l:740", "s:600", SuggestedType.TEAM)
        ))
        items.add(SuggestedPlayer(
                "http://i.espncdn.com/i/players/130x180/22774.jpg",
                "Cristiano Ronaldo",
                "SOCCER",
                "19e162c06bf5d817e9f981bf96001ee2",
                buildAnalyticsPlayer("s:600~t:111", "s:600~l:730", "s:600", SuggestedType.LEAGUE)
        ))
        return items
    }

    private fun  buildAnalyticsPlayer( teamUid:String?,  leagueId :String,  sportUid :String,  suggestedType:SuggestedType):PlayerAnalytics {
        return  PlayerAnalytics(teamUid, leagueId, sportUid, suggestedType)
    }

     private fun presentTopHeader():TopBrowsePlayerHeader {
        val  searchURL = "http://someurl"
        return  TopBrowsePlayerHeader("Player Browse", searchURL)
    }

     private fun buildAnalytics():Analytics {
        return  Analytics(null, null, null, null, null, PageType.ALL_PLAYERS, false)
    }

    private fun buildMockEntitiesBrowse(): List<EntityBrowse> {
        var items = arrayListOf<EntityBrowse>()
        items.add(buildSport("NFL", "s:20~l:28", "http://a.espncdn.com/i/teamlogos/leagues/500/nfl.png"))
        items.add(buildSport("NCAA Football", "s:20~l:23", "http://a.espncdn.com/redesign/assets/img/icons/ESPN-icon-football-college.png"))
        items.add(buildSport("NBA", "s:40~l:46", "http://a.espncdn.com/i/teamlogos/leagues/500/nba.png"))
        items.add(buildSport("NCAA Basketball", "s:40~l:41", "http://a.espncdn.com/redesign/assets/img/icons/ESPN-icon-basketball.png"))
        return items
    }

    private fun buildSport(label: String, uid: String, image: String): EntityBrowse {
        val type = "internalLink"
        val url = "sportscenter://x-callback-url/showPlayerBrowse?uid=$uid"
        val action = BrowsePlayerAction(type, url)
        return  EntityBrowse(label, UID.create(uid), action, image)
    }

I'm not really now how can I send the transaction and apiRequest mocked objects to the controller because I am only calling this.mockMvc!!.perform(get("/v1/browse/players/{transaction}{apiRequest}",transaction,apiRequest) without send any param.

Any ideas?

difference between unit/integration test and component/functional test

I'm java dev and understand unit test and integration test well, but at this place they used Jbehave framework and divides the tests to component and functional tests, which confused me. my questions are:

  1. is it true that unit and integration tests are whitebox testing while component and functional tests are blackbox testing?

  2. I read some internet post about functional test, it's high level test for system like web app + backend api service, but our system is a pure backend service, we push data to event hub, then run the server which pull data out of event hub and push to database. I just don't see what kind of functional tests i can create for this. it's exactly an integration test + some BDD story description.

  3. For real BDD, shouldn't the PO/PM or BA create the scenario/stories then dev develop the test codes? here we as developers do both, so feel really like writing integration tests plus some extra words

anyone can explain this?

Are threre Java test frameworks with collections of tests (for simple classes)?

I am looking for test frameworks containing tests for e.g. classes like Map and Collection or methods like equals(Object) and hashCode.

Is there a way to disable bundling for Karma tests in Angular?

I'm working on a big Angular project that has more than 4000 Unit Tests. Starting the tests takes round about 100 - 120 seconds before the first test begins to run. Presently, we use Karma and Jasmine for the tests.

Is there a way to disable bundling the project for the tests? Using Jest is maybe an alternative because it does not bundle the project. But when I want to use Jest I have to correct more than 800 tests.

Here are some additional Information about the used versions:

  • Angular 7.2
  • Karma 4.0
  • Jasmine 3.4
  • Webpack 4.29 (no custom webpack config)

Cleaning smart contract storage after running a test case

When running test cases for a Smart Contract I would like to either destroy the smart contract and redeploy it or reset its state after each test case is run. The test cases are written in javascript. The idea would be to run the code inside the AfterEach structure.


contract("Contract", accounts => {
  let contract;
  let owner = accounts[0];
  let admin = accounts[1];
  let user = accounts[2];

  describe("function1 tests", () => {
    beforeEach("Setup contract for each test", async () => {
      contract = await Contract.deployed();
    });

    afterEach("", async () => {
     //code to selfdestruct or reset the state of the contract after 
     //each test
    });

    it("test1", () => {
      //test1 code
    });

    it("test2", () => {
      //test2 code
    });
  });
});

unable to open the play store on real devices

Getting the error message while executing the code.

I tried to add the JAR file, Set up Environment variable but nothing is working.

public class test {

    public static void main(String[] args) throws Exception {

        //Set the Desired Capabilities
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("deviceName", "Galaxy S9+");
        caps.setCapability("udid", "352402097079489"); //Give Device ID of your mobile phone
        caps.setCapability("platformName", "Android");
        caps.setCapability("platformVersion", "9.0");
        caps.setCapability("appPackage", "com.example.android.myAPP,com.android.settings");
        caps.setCapability("appActivity", "com.google.android.finsky.activities.MainActivity");
        caps.setCapability("noReset", "true");
        try {
            //  System.setProperty("webdriver.http.factory", "apache");
            AppiumDriver < MobileElement > driver = new AndroidDriver < MobileElement > (new URL("http://localhost:4723/wd/hub"), caps);

        } catch (MalformedURLException e) {
            System.out.println(e.getMessage());
        }
    }

}

Exception in thread "main" java.lang.NoSuchMethodError: org.openqa.selenium.remote.http.HttpClient$Factory.createDefault()Lorg/openqa/selenium/remote/http/HttpClient$Factory;

How to test Spring RestController with HandlerInterceptorAdapter applied?

I am developing a Spring web service. I want to test my endpoints but for some reason I always get the following exception when I run the tests:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....IncomingInterceptor' 

However, I annotated the class with @Component. The interceptor works when I test the endpoint using an external client! Does somebody know how to solve this problem?

Here is my code when I test the endpoint: private MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@Mock
private IncomingFilter incomingFilter;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingFilter).build();
}

@Test
public void testAddAccount() throws 
    mockMvc.perform(MockMvcRequestBuilders.post("/account/add")
            .content(gson.toJson(account))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNotEmpty());
}

Thanks in advance!