dimanche 30 septembre 2018

testing a method with events in a repository with phpunit laravel

Hello everyone I am looking for help as I am starting on unit testing Laravel.

Here is the repository method I am testing =>

   public function store(array $input){

            $input['billing_contact'] = (isset($input['billing_contact'])) ? 1 : 0;  
            \DB::beginTransaction();
            try {
                $new_contact = $this->model->create($input);

                //EVENT CREATE ACCOUNT (USER)
                event(new EventCreateUserWithContact($new_contact));
                \DB::commit();
            }
            catch(\Exception $e){
                \DB::rollback();
                return false;
            }


            return $new_contact;

        }

Here is the test that I am trying to make =>

class ContactTest extends TestCase
{
    use WithFaker;
    protected $contact;/**/
    protected $container;/**/

    public function setup()
    {
        parent::setup();
        $this->container = new \Illuminate\Container\Container();
        $this->contact = new Contact();
        DB::beginTransaction();
    }
    public function tearDown()
    {
        DB::rollback();
        parent::tearDown();
    }
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testContactRepo()
    {
//        Event::();
        $publisher = factory(\App\Models\Publisher::class)->create();
        $contact =  factory(\App\Models\Contact::class)->create();


//
        $data =  [

            'first_name' => $this->faker->word,
            'last_name'=>  $this->faker->word,
            'email' => $this->faker->unique()->safeEmail,
            'phone'=> 112321321,
            'job'=> $this->faker->word,
            'billing_contact'=> $this->faker->word,
            'approve_delete_at'=> $this->faker->date('Y-m-d',  '1461067200'),
            'publisher_id'=> $publisher->id,

        ];

        $rep = new ContactRepositoryEloquent($this->container);

        $contact = $rep->store($data);
    dd($contact);


    }
}

I do not understand how to get to => " return $new_contact;" I got an exception error when I run the test (I get false) Do I need to create a fake event to make it works?

Thank you again for your help[ it will be much appreciated

Can Postman Variables be Passed Into Header?

I am trying to string a few Postman requests together for testing.

  1. In the first request I set a global variable as a test script.

    tests['Status code is 200'] = (responseCode.code === 200);
      if (responseCode.code === 200) {
      try {
        let jwt = responseBody.replace(/"/g, '');
        pm.globals.set("jwt", jwt);
        console.log("Variable will be set to", jwt);
      }
      catch(e) {
        console.log(e);
      }
    }
    
    
  2. In the second request I run a pre-request script as

    let jwt = pm.globals.get("jwt");
    
    

Then I try to pass it into the header

enter image description here

Is it possible to pass a value into the header?

When running tests the second request fails due to having an invalid jwt, and the Postman docs only show examples passing variables into the URL.

How to structure imports in Golang test files

I have an application with multiple binaries:

myapp/cmd/app/main.go
myapp/cmd/cli/main.go

I currently have a lot of simple unit test logic I run in the func main of the main.go files. I'm just testing individual functions and having them print their output, I'm not trying to invoke the whole power of the "testing" suite, if I can avoid it.

Since my tests in the top of my main.go are so long at this point, I would like to move them to specific test files, in for example:

myapp/cmd/app/main_test.go
myapp/cmd/cli/main_test.go

This works well enough with my makefile:

# Makefile

all: test build
build:
    go build -o cmd/app/main cmd/app/main.go
    go build -o cmd/cli/main cmd/cli/main.go
test:
    go test ./cmd/app/main_test.go
    go test ./cmd/cli/main_test.go

If I just want to run my testfiles, I'd like to take the item in my app/main.go

// cmd/app/main.go
package main

func definedInMain(m string) string {
  // 
}

func main() {
  m := definedInMain("1")
  fmt.Println()
  // all the rest of my app's logic...
}

And run it in my main_test.go

// cmd/app/main_test.go

package main

// no imports, I hope?

func testDefinedInMain() {
  m := definedInMain("1")
  fmt.Println()  
}

However, this fails with:

undefined: definedInMain
FAIL

I am confused that I have to import all these functions into my main_test.go files (and even when I try, it suggests "can't load package: ... myapp/cmd/app/main" in any of: ...")

Is there a clean and go-idiomatic way for me to test my very simple unit tests in test files and run my functions in main files without a lot of rewriting imports or other substantial re-architecting?

From some links, I had the impression if I made a main_test.go, the imports would follow on their own (as they seem to in these examples).

So, you can see I am a bit confused tutorials get their functions imported for free, and I do not, and I just want to understand the magic better.

Difference between dd-path testing and basis path testing?

I've read lot of resources. But I still don't get the atomic point of differences between both of them. What makes me confuse are:

1) both dd-path and basis path aims for branch coverage. So what is the difference ?

2) DD-path means (branch coverage or C2). Can we call Basis Path C2 ?

3) Most software engineering books (sommerville, pressman) doesn't mention dd-path. most of them use Basis Path. Is dd-path somewhat not used anymore ?

4) It's said that BP(basis path) can cover all statement without all exhausting path. didn't branch coverage of dd-path do the same ?

5) we can get 'independent path' without V(G). We already know how to get it without any formula (just don't repeat the path that already traversed)

6) MCCabe purposed Cyclomatic Complexity in 1976. With original aims for calculating software complexity. Thus if any module exceed the limit. It must be separated. CC doesn't created for software testing until He realize that the value of V(G) can find the 'basis' path in 1996

7) Any of you can give explanation with simple code and test case for dd-path testing and BP testing ?. branch coverage ≤ cyclomatic complexity ≤ number of paths. But any example ? I've seen branch coverage test case simmiliar with BP test case.

I have read pressman, sommervile, lot wikipedia page, slides from various colleges (spent 2-3 days without getting answers. just many scattered points). But I am still can't get the atomic point of difference between them

Thank you very much.

How to Set Variable from Request in Postman

I am trying to write some tests for Postman. Many of the requests require an API key that gets returned by an initial GET request.

To set something hard-coded that is not dynamic, it looks like the test code is of the form

let variable = pm.iterationData.get("variable");
console.log("Variable will be set to", variable);

How do I set a return value as a global variable and then set that as a header parameter?

How can I stop a MySQL docker container which populates a volume after database initialisation is complete?

I have a docker-compose.yml file with the following:

 populated_db:
        container_name: populated_db
        restart: always
        image: mysql
        volumes:
            - ./test_database.sql:/docker-entrypoint-initdb.d/a.sql
            - populated_test_db:/var/lib/mysql
        ports:
            - "33061:3306"
        environment:
            MYSQL_RANDOM_ROOT_PASSWORD: "true"
            MYSQL_DATABASE: aaaa
            MYSQL_USER: aaaa
            MYSQL_PASSWORD: aaaa
db:
    container_name: db
    image: mysql
    ports:
        - "33060:3306"
    volumes:
        - type: volume
          source: populated_test_db
          target: /var/lib/mysql
          volume:
            nocopy: false
    restart: always
    environment:
        MYSQL_RANDOM_ROOT_PASSWORD: "true"
        MYSQL_DATABASE: aaaa
        MYSQL_USER: aaaa
        MYSQL_PASSWORD: aaaa
    depends_on:
        - populated_db

volumes:
    populated_test_db:

The populated_db container successfully starts and populates the database with the contents of test_database.sql. However, once it has done that, the db container starts and tries to use populated_test_db as its /var/lib/mysql, causing the following error:

Unable to lock ./ibdata1 error: 11
Check that you do not already have another mysqld process using the same InnoDB data or log files.

Presumably this is because the populated_db container is still running. How can I stop it running once it has populated the volume, so the db container can use the populated volume?

How to override class behaviour in a JUnit test

I am trying to create JUnit tests for a method in class A, that creates an instance of class B. Since, I want to isolate the method's behaviour, I would like to override B's methods in my test suite for A with simpler ones, that would work for the purposes of testing A.

I have tried doing so using Mockito's Spy, however as I understand it only allows to return a static value upon a method call, however I need to replace complex external logic with simpler one, while taking into account the parameters passed.

What is the best way to approach this?

How do I get the method and the string on the same line with a puts statement in Ruby?

The code below prints out the result that I want but the problem is that the tests are expecting a puts statement. This is the error message I get:

Failure/Error: expect($stdout).to receive(:puts).with("The line is currently: 1. Amanda 2. Annette 3. Ruchi 4. Jason 5. Logan 6. Spencer 7. Avi 8. Joe 9. Rachel 10. Lindsey")

   (#<IO:<STDOUT>>).puts("The line is currently: 1. Amanda 2. Annette 3. Ruchi 4. Jason 5. Logan 6. Spencer 7. Avi 8. Joe 9. Rachel 10. Lindsey")
       expected: 1 time with arguments: ("The line is currently: 1. Amanda 2. Annette 3. Ruchi 4. Jason 5. Logan 6. Spencer 7. Avi 8. Joe 9. Rachel 10. Lindsey")
       received: 0 times

How do I get the method and the string to display on the same line with a puts statement in Ruby?

Here's my code:

def line (katz_deli)

    if katz_deli.empty?  
       puts "The line is currently empty." 
    else
       print "The line is currently: "

       katz_deli.each_with_index{|name, index| 
       print "#{index + 1}. #{name}"
        }
    end

end

I've tried creating a variable and it doesn't print out the index only the array; I've tried using puts which just prints the array and index on the next line obviously so it brings up the error message.

Thanks so much for your help x

How would you go about testing a method with a private threshold?

Image a following situation:

private final double THRESHOLD = 10d;
public boolean isHighEnough(double numberOfPeople, double arg2, ...) {
    return Math.pow(numberOfPeople) / 3 * arg2 ... >= THRESHOLD;
}

When writing tests for isHighEnough would you write something besides min (numberOfPeople = 0, arg2 = 0) and maxCase (numberOfPeople = 10^9), it's difficult to write a medium test because THRESHOULD may be changed soon ( first it's heuristically).

Thanks.

select_related on nullable fields does not work as expected in view

I am using select_nullable in a Django view to retrieve a relationship that can be null

nullable foreign keys must be specified

So I am explicitely passing it as a parameter:

source_text = get_object_or_404(Text.objects.select_related('language'), pk=source_text_pk) 

The problem is that when I'm accessing it in a template it generates a database query, i.e.:

# items/templates/items/source.html


Testing it with:

    # items/tests/test_views.py
    ...
    source_text = TextFactory()
    context = {'source': source_text}
    with self.assertNumQueries(0):
        # render the template with given context to trigger possible db hits
        from django.template.loader import render_to_string
        rendered = render_to_string("items/source.html", context)

Generates:

...
AssertionError: 1 != 0 : 1 queries executed, 0 expected
Captured queries were:
1. SELECT "languages_language"."id", "languages_language"."name", "languages_language"."code" FROM "languages_language" WHERE "languages_language"."id" = 16

Involved models are defined as:

# items/models.py
class Text(models.Model):
    language = models.ForeignKey('languages.Language', 
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True)
# languages/models.py
class Language(models.Model):
    name = models.CharField(max_length=200)
    code = models.CharField(max_length=35)
    def __str__(self):
       return "name: {} \tcode: {}".format(self.name, self.code)

How should I use select_related to not generate a database query in the view?

need a topic for ms research in software testing/software quality

i am interested in research in software testing in quantitative research. Which topics in software testing should i consider in research and also provide research papers on software testing.

Need Explanation for Multiple condition coverage testing

How many different test cases would you need to achieve multiple condition coverage

if (A&&B||(Delta<1)&&(up<down)||(Right>=Left))
{
Execute some statements ;

}
Else
{

some statements;

}

Tried with 2 Power n where n = no. of conditions. Am not getting the answer.

What is the best design for unittes UI pages?

I have used many approaches in .Net Framework WebForms,Mvc,Angular and so on. But non of them do not propose simple way to test UI pages logic.

Lets imagine simple web page where we have two comboboxes country and state. When country change selected value state combobox should change its content and have appropriate states.

In my opinion the best solution is to have component which already contais this two comboboxes and server side code. At least we could test this component once manualy and then use it several times at project. But is is not universal and flexible solution.

What is the best design of such web UI to have clear and simple unit test of this scenorio ?

samedi 29 septembre 2018

Android Phone Test Local Web Application

I made a web application using Vue + Nginx + Node and I want to test them on the mobile phone.

How can I access the pc local applications from the android phone and successful make request on the Client side?

I tried so many methods like listen on localhost, access through Wifi. But this way I cannot make any request from the Client side. Chrome port forwarding, the request just hang.

Python Coverage - not covering function contents, just definition

I am using coverage.py to test my code coverage. My tests are passing, however, when I call

coverage run -- [script].py -m [test_script].py

and generate a report it indicates that

<line hits="1" number="5"/>
<line hits="0" number="6"/>
<line hits="0" number="7"/>
<line hits="0" number="8"/>

Where line 5,6,7 and 8 are as follows:

def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

For another example:

My test code:

def test_arb():
assert tree.inc(3) == 4

the function

def inc(x):
    return x+1

and the result on the report

<line hits="1" number="48"/>
<line hits="0" number="49"/>

I've spent days researching this and can't seem to find a straightforward answer. Would anyone be able to help? It may be an obvious fix but I am a beginner at Python and testing.

Golang -coverprofile excluding untested files from coverage percentage

I'm trying to run a test coverage report on my project which contains several directories (I'm aware this is an unusual setup but it has lots of examples which I want to group together):

└── example
    ├── bar
    │   └── main.go
    ├── baz
    │   └── main.go
    ├── foo
    │   ├── main.go
    │   └── main_test.go
    └── qux
        └── main.go

However when it run I get some strange output. The coverage percentage seems to only related to the only tested file - not the entire codebase under example.

For instance:

$ go test -race -v -coverprofile .test-coverage.txt ./...
?       github.com/abcdef/example/bar    [no test files]
?       github.com/abcdef/example/baz      [no test files]
=== RUN   TestSum
--- PASS: TestSum (0.00s)
PASS
coverage: 50.0% of statements
ok      github.com/abcdef/example/foo     1.018s  coverage: 50.0% of statements
?       github.com/abcdef/example/qux    [no test files]

Does anyone know why this is happening and whether there's a way I can make it generate a percentage coverage across all files, including any untested files? Otherwise the coverage percentage is completely misleading.

PHPUnit Framework - Should I include variables in setup() that appear in some but not all functions

Say I have a test file:

ExampleClassTest.php

And the test file has 3 functions:

public function testOne {
     $testVariable = 1;
     // Assert something
}

public function testTwo {
     $testVariable = 1;
     // Assert something
}

public function testThree {
     // Assert something
}

The first two functions have a shared variable:

$testVariable = 1;

How ever the third one does not. Is it good practice to have the shared variable in setup:

setUp() {
     $testVariable = 1;
}

To save repeating code?

Obviously, it is not being used by all functions.

I know it works either way, this is purely from a framework/coding practice perspective.

vendredi 28 septembre 2018

How to provide stdin for doctests?

I want to create an example in doctest for using getLine. However, when I run the test, it does not terminate:

{- |
>>> getLine
>>> Hello, World!
"Hello, World!"
-}
module MyModule where

How to provide custom input for doctest?

Testing Alarms for a Chrome/browser extension

I'm writing a Chrome extension that uses alarms quite heavily. I want to create test suite, but to do this effectively, I'd need to be able to simulate changing the time as far as the browser sees it, so that I can test alarms firing in certain conditions. What is the nicest/easiest way to do this?

Rails form testing: post directly or through form?

Most examples of Rails tests I have seen post directly to a url. I found out recently that Rails supports the manipulation of form elements using 'fill_in' and 'click_on'.

Should I be posting directly or submitting through the forms manually? Filling in the forms manually seems much more thorough, and the reason I ask is, well, all the examples I've seen are posting directly. Obviously there may be a little less work with posting directly, but I'm curious what cases I might be missing. Is there a best practice?

How to run all tests in a nested directory in Android Studio. Error: 0 tests classes found in package

I have tests in Android Studio that I can run individually. However I can't run all tests in a directory. I get the following error:

0 test classes found in package '<default package>'

My tests are following the package structure of the app, so they are in directories such as this:

/test/java/myapp/
    domain/
        MyDomain1Tests.kt
        MyDommain2Tests.kt
    ui/
        MyUi1Tests
        MyUi2Tests

Does Android Studio support this? Surely it must, but I can't find out how.

Looking for WinForms Automation Framework (.NET 2.0 Compatible)

I am looking for an automation framework that can test a legacy WinForms app running under .NET 2.0 via the GUI. Our software runs on Windows 7 Embedded and communicates with a bunch of different hardware, which have not been mocked in our development environment. Because of this, any testing software we create must also run on Windows 7 Embedded with our software. We are stuck using .NET 2.0 on our Windows 7 Embedded device because of scheduling and hardware limitations (i.e. there is very limited flash drive space on our device, so installing higher versions of .NET would take up valuable space that we need). Is there an automation framework for testing WinForms at the GUI level which is also .NET 2.0 compatible? Thanks!

Mockito : how to mock an autowired variable while testing

I'm unit testing my web application using JUnit and Mockito. At the moment i'm trying to write testcases for Service layer after completing the DAO level. This is my test case:

package it.ingeniars.testService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static org.mockito.Mockito.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.assertj.core.api.Assertions.*;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

import it.ingeniars.constants.EasycareEnumTypes.ActivityType;
import it.ingeniars.dao.interf.AccountDAOInterface;
import it.ingeniars.dao.interf.CareTeamDAOInterface;
import it.ingeniars.dao.interf.DeviceDAOInterface;
import it.ingeniars.dao.interf.ObservationDAOInterface;
import it.ingeniars.dto.DeviceDTO;
import it.ingeniars.dto.ObservationDTO;
import it.ingeniars.exception.ECForbiddenException;
import it.ingeniars.mapper.DeviceMapper;
import it.ingeniars.mapper.ObservationMapper;
import it.ingeniars.model.Account;
import it.ingeniars.model.Device;
import it.ingeniars.model.Observation;
import it.ingeniars.service.DeviceService;
import it.ingeniars.service.ObservationService;
import it.ingeniars.testConf.MockDAOUtils;
import it.ingeniars.testConf.MockDTOUtils;
import it.ingeniars.testConf.TestContext;
import it.ingeniars.utilities.DatetimeUtils;
import it.ingeniars.utilities.SessionVariable;

@ContextConfiguration(classes = {TestContext.class})
@ComponentScan({"it.ingeniars.service"})
public class ObservationServiceTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Autowired
    private MockDAOUtils mockDAOUtils;

    @Mock
    SessionVariable sessionVariable;

    @Mock
    private ObservationDAOInterface observationDAOMock;

    @Mock
    private AccountDAOInterface accountDAOMock;

    @Mock
    private CareTeamDAOInterface careTeamDAOMock;

    @Spy
    private ObservationMapper mapper;

    @InjectMocks
    private ObservationService service;

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

    /**
     * {getObservationList}
     * 
     * [account]
     * -------------------------------------------------------------------------------------------------------
     * | id   | enabled | locked | account_expired | password_expired | data_handling | role                 |
     * -------------------------------------------------------------------------------------------------------
     * | 1000 | 1       | 0      | 0               | 0                | 1             | patient              |  targetAccount : valid patient account
     * | 1001 | 1       | 0      | 0               | 0                | 1             | general_practitioner |  callerAccount : medic in patient careteam
     * | 1002 | 1       | 0      | 0               | 0                | 0             | patient              |  targetAccount : invalid patient account
     * | 1003 | 1       | 0      | 0               | 0                | 1             | patient              |  callerAccount : patient with ID different from patientID
     * -------------------------------------------------------------------------------------------------------
     * 
     * [Observation]
     * ------------------------------------------------------------------------
     * | id | activity_type | medical_record_id | execution_date      | Note  |
     * ------------------------------------------------------------------------
     * | 1  | act_pressure  | 1                 | 2018-06-01 11:00:00 | Note1 |
     * | 2  | act_oximetry  | 1                 | 2018-06-01 14:00:00 | Note2 |
     * ------------------------------------------------------------------------
     * 
     */
    @Test
    public void test_case_u0048() throws Exception {

        // Taking method name
        String methodName = new Object() {
        }.getClass().getEnclosingMethod().getName();
        // Building test case file path
        String path = mockDAOUtils.getTc_path() + methodName + mockDAOUtils.getXml_ext();

        // Setting the test environment
        List<Account> accountList = mockDAOUtils.mockAccount(path);
        List<Observation> observationList = mockDAOUtils.mockObservation(path);
        List<ActivityType> activityTypeList = new ArrayList<ActivityType>();
        activityTypeList.add(ActivityType.act_pressure);
        activityTypeList.add(ActivityType.act_oximetry);
        Date startDate = mockDAOUtils.getFormat().parse("2018-06-01 00:00:00");
        Date endDate = mockDAOUtils.getFormat().parse("2018-06-01 23:59:59");


        // [RESULT CASE - VALID TARGET ACCOUNT / MEDIC CALLER ACCOUNT IN PATIENT CARE TEAM]
        Mockito.when(accountDAOMock.findByPersonId(1000L)).thenReturn(accountList.get(0));
        Mockito.when(careTeamDAOMock.isCareTeam(1000L, 1001L)).thenReturn(true);
        Mockito.when(sessionVariable.getTimezone()).thenReturn("GMT-8:00");
        System.out.println("[SV] = " + sessionVariable.getTimezone());
        Mockito.when(observationDAOMock.getListByMedRecIdAndActivityTypeAndDateRange(1L, activityTypeList, startDate, endDate)).thenReturn(observationList);
        List<ObservationDTO> observationDTOList = service.getObservationList(1000L, accountList.get(1), activityTypeList, startDate, endDate);

    }

}

Service Layer :

package it.ingeniars.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import it.ingeniars.constants.EasycareEnumTypes.ActivityType;
import it.ingeniars.constants.EasycareEnumTypes.ApplicationRole;
import it.ingeniars.dao.interf.AccountDAOInterface;
import it.ingeniars.dao.interf.CareTeamDAOInterface;
import it.ingeniars.dao.interf.ObservationDAOInterface;
import it.ingeniars.dto.ObservationDTO;
import it.ingeniars.exception.ECForbiddenException;
import it.ingeniars.exception.ECNotFoundException;
import it.ingeniars.mapper.ObservationMapper;
import it.ingeniars.model.Account;
import it.ingeniars.model.Observation;
import it.ingeniars.utilities.DatetimeUtils;
import it.ingeniars.utilities.SessionVariable;

@ComponentScan({"it.ingeniars.mapper","it.ingeniars.dao.impl"})
@Service
@Transactional
public class ObservationService {

    @Autowired
    ObservationDAOInterface observationDAO;

    @Autowired
    SessionVariable sessionVariable;

    @Autowired
    ObservationMapper observationMapper;

    @Autowired
    AccountDAOInterface accountDAO;

    @Autowired
    CareTeamDAOInterface careTeamDAO;

    /**
     * Provide the list of ObservationDTO of the patient included in the period and matching the list of types
     * 
     * @param patientId id of the patient
     * @param activityTypes list of activity types
     * @param startDate beginning of the period
     * @param endDate end of the period
     * @return the list of observations, eventually empty
     * 
     */

    @Transactional(readOnly=true)
    public List<ObservationDTO> getObservationList(long patientId, Account callerAccount, List<ActivityType> activityTypes, Date startDate, Date endDate){  

        // target permission check      
        Account targetAccount = accountDAO.findByPersonId(patientId);
        if(targetAccount == null) {
            throw new ECNotFoundException();
        } else if (!targetAccount.isValid()){
            throw new ECForbiddenException();
        } else if (targetAccount.getFirstApplicationRole() != ApplicationRole.patient) {
            throw new ECForbiddenException();
        }

        // caller permission check
        switch (callerAccount.getFirstApplicationRole()) {
            case general_practitioner:
            case medical_specialist:
                if(!careTeamDAO.isCareTeam(targetAccount.getId(), callerAccount.getId())) {
                    throw new ECForbiddenException();
                }
                break;
            case patient:
                if(targetAccount.getId() != callerAccount.getId()){
                    throw new ECForbiddenException();
                }
                break;
            default:
                throw new ECForbiddenException();       
        }

        List<Observation> observationList = observationDAO.getListByMedRecIdAndActivityTypeAndDateRange(targetAccount.getMedicalRecord().getId(), activityTypes, startDate, endDate);
        List<ObservationDTO> observationDTOList = new ArrayList<>();

        for(Observation item : observationList){
            observationDTOList.add(observationMapper.convertToDTO(item));
        }

        return observationDTOList;      
    }

}

Mapper:

package it.ingeniars.mapper;

import java.util.Map;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import it.ingeniars.constants.EasycareEnumTypes.ObservationExamType;
import it.ingeniars.constants.EasycareEnumTypes.ObservationParameterType;
import it.ingeniars.dto.ObservationDTO;
import it.ingeniars.dto.ScalarObservationDTO;
import it.ingeniars.dto.SignalObservationDTO;
import it.ingeniars.model.Observation;
import it.ingeniars.model.ObservationScalar;
import it.ingeniars.model.ObservationSignal;
import it.ingeniars.utilities.DatetimeUtils;
import it.ingeniars.utilities.SessionVariable;

@Component
public class ObservationMapper extends Mapper<ObservationDTO,Observation> {

    @Autowired
    SessionVariable sessionVariable;

    @Autowired
    ScalarObservationMapper scalarMapper;

    @Override
    public ObservationDTO convertToDTO(Observation entity) {
        ObservationDTO observationDTO = new ObservationDTO();
        observationDTO.setActivityType(entity.getActivityType());
        observationDTO.setActivityLabel(entity.getActivityType().getLabelCode());
        //observationDTO.setScheduleActivityId(entity.getScheduleActivity() != null ? entity.getScheduleActivity().getId() : null);
        observationDTO.setMedicalRecordId(entity.getMedicalRecord().getId());
        System.out.println("[SV] = " + sessionVariable.getTimezone());
        observationDTO.setExecutionDate(DatetimeUtils.dateToDatetimeISO8601(entity.getExecutionDate(),TimeZone.getTimeZone(sessionVariable.getTimezone())));
        observationDTO.setId(entity.getId());
        observationDTO.setNote(entity.getNote());

        for(ObservationScalar entityScalarObs : entity.getScalarObservationList()){
            ScalarObservationDTO scalarObsDTO = scalarMapper.convertToDTO(entityScalarObs);         
            observationDTO.getScalarObservationList().put(scalarObsDTO.getParameterType(), scalarObsDTO);
        }

        SignalObservationMapper signalMapper = new SignalObservationMapper();
        for(ObservationSignal entitySignalObs : entity.getSignalObservationList()){
            SignalObservationDTO signalObsDTO = signalMapper.convertToDTO(entitySignalObs);         
            observationDTO.getSignalObservationList().put(signalObsDTO.getType(), signalObsDTO);
        }

//      Hibernate.initialize(observationDTO.getScalarObservationList());
//      Hibernate.initialize(observationDTO.getSignalObservationList());
        return observationDTO;
    }

    @Override
    public Observation convertToEntity(ObservationDTO dto) {
        Observation observation = new Observation();
        observation.setActivityType(dto.getActivityType());
        observation.setExecutionDate(DatetimeUtils.stringToDate(dto.getExecutionDate()));
        observation.setNote(dto.getNote());

        for(Map.Entry<ObservationParameterType,ScalarObservationDTO> scalarObsDTO : dto.getScalarObservationList().entrySet()){
            if (scalarObsDTO.getValue() != null){//empty field
                observation.getScalarObservationList().add(scalarMapper.convertToEntity(scalarObsDTO.getValue()));
            }
        }

        SignalObservationMapper signalMapper = new SignalObservationMapper();
        for(Map.Entry<ObservationExamType,SignalObservationDTO> signalObsDTO : dto.getSignalObservationList().entrySet()){
            if (signalObsDTO.getValue() != null){
                observation.getSignalObservationList().add(signalMapper.convertToEntity(signalObsDTO.getValue()));
            }
        }       

        return observation;
    }

    @Override
    public void updateEntity(ObservationDTO dto, Observation entity) {
        // TODO Auto-generated method stub

    }

}

My problem comes while trying to test the "getObservationList" method of the Service : everything I mocked works good until I go to the mapper, where i got NullPointerException here

observationDTO.setExecutionDate(DatetimeUtils.dateToDatetimeISO8601(entity.getExecutionDate(),TimeZone.getTimeZone(sessionVariable.getTimezone())));

I think that the sessioVariable is null due to the fact that it isn't initialized in my test context, so I'm trying to mock o do some stuff to let me have a valid sessionVariable (the content is not important at this moment) not modifying nothing in Service and Mapper.

Thanks in advance! Bye!

Where to put tests for subpackages in python?

When a python module has multiple subpackages, where should tests for features in those subpackages be placed?

I can see two ways it could be done:

  • Create a separate test folder in each subpackage and place its tests there.
  • Duplicate the package hierarchy in the top-level test folder, placing the tests for each subpackage in the corresponding folder.

However it's not clear which option should be preferred.

For a package foo arranged like this:

foo/
  __init__.py
  bar.py
  baz/
    __init__.py
    baz.py

Do I put the tests here?

foo/
  __init__.py
  bar.py
  baz/
    __init__.py
    baz.py
  test/
    __init__.py
    test_bar.py
    baz/
      __init__.py
      test_baz.py

Or here?

foo/
  __init__.py
  bar.py
  baz/
    __init__.py
    baz.py
    test/
      __init__.py
      test_baz.py
  test/
    __init__.py
    test_bar.py

Testing a fs library function with Jest/Typescript

I am trying to test a library function that I have written (it works in my code) but cannot get the testing with the mock of the fs to work. I have a series of functions for working with the OS wrapped in functions so different parts of the application can use the same calls.

I have tried to follow this question with mocking the file system, but it does not seem to work for me.

A short sample to demonstrate the basics of my issue are below:

import * as fs from 'fs';
export function ReadFileContentsSync(PathAndFileName:string):string {
    if (PathAndFileName === undefined || PathAndFileName === null || PathAndFileName.length === 0) {
        throw new Error('Need a Path and File');
    }
    return fs.readFileSync(PathAndFileName).toString();
}

So now I am trying to test this function using Jest:

import { ReadFileContentsSync } from "./read-file-contents-sync";
const fs = require('fs');

describe('Return Mock data to test the function', () => {
    it('should return the test data', () => {
        const TestData:string = 'This is sample Test Data';

// Trying to mock the reading of the file to simply use TestData
        fs.readFileSync = jest.fn();                
        fs.readFileSync.mockReturnValue(TestData);

// Does not need to exist due to mock above     
        const ReadData = ReadFileContentsSync('test-path');
        expect(fs.readFileSync).toHaveBeenCalled();
        expect(ReadData).toBe(TestData);
    });
});

I get an exception that the file does not exist, but I would have expected the actual call to fs.readFileSync to not have been called, but the jest.fn() mock to have been used.

ENOENT: no such file or directory, open 'test-path'

I am not sure how to do this mock?

Performance testing in neoload

I am new to performance testing and I have a scenario in which there is an interviewer login in into the application and conducting an interview with the client.the candidate has to login at the same time and enter into the same interview session with the interviewer.can any1 please help me with how I can record the scenario.

Thanks.

Caffe Googlenet example: deploy.prototxt has dropout?

I am trying to understand the deploy.prototxt example under Caffe's blvc_Googlenet

While trying to solve this problem I have: Caffe error while testing: Check failed: count_ == proto.data_size() (9408 vs. 0) I have gone through the deploy.prototxt already provided.

  1. Why does the deploy example have dropout layer? Is not it something we need just for training?
  2. Since it is Googlenet, we have 3 losses (train_val.prototxt), I basically got rid of them all in deploy.prototxt but the last, as I only need the final prediction:

    layer { name: "loss3/classifier" type: "InnerProduct" bottom: "pool5/7x7_s1" top: "loss3/classifier" inner_product_param { num_output: 7 weight_filler { type: "xavier" } bias_filler { type: "constant" value: 0 } } }

    layer { name: "prob" type: "Softmax" bottom: "loss3/classifier" top: "prob" }

But I now wonder if I should keep the previous loss layers?

I have done training/testing with caffe using deploy.prototxt before but I seem to have trouble with Googlenet so I think I might be missing something. Sorry I can't articulate the problem better as I don't have much clue why it fails.

GoogleTest tests declare in separate library

I have a lot of auto-generated tests using the GoogleTest framework. Currently each test is in a .cpp file which is inclued in a larger "Tests.cpp" file, which is then included in the main file. When trying to compile all of them my computer freezes. I've assumed it is because it is trying to compile them in a single output file. Is there a way to write each test fixture in a "normal" way, having an output file for each test fixture/case and then linking them?

Thanks

Kerning issues with headless chrome

Running some selenium tests that involve screenshot based assertions and running to the following issue:

enter image description here

For some reason headless chrome (v69 on ubuntu 16.04) screws up kerning and as a result the screenshots end up being quite different, more than the 1% threshold I've set.

Groovy/Grails Proliferation of "\" escape character

This is a rather odd issue. I'm integration testing a Grails service and the associated domain class. One property of that domain class is a String that holds a JSON. The database field is json too and there's a custom Hibernate value type that performs the necessary conversion. It's already been working for years in production in another domain class.

class MyDomain {
    String data
    static mapping = {
        data type: StringJsonUserType
    }
}

So far so good. In my test I mock an input object to my service method that ultimately will contain and return the desired JSON string.

private MockedClass mockClass() {
    // JsonRepresentable declares asJson() method.
    def data = GroovyMock(JsonRepresentable)
    data.asJson() >> "{\"content\":\"irrelevant\"}"

    def mockClass = GroovyMock(MockedClass)
    mockClass.getData() >> data

    return mockClass
}

The service method (simplified):

void persist(MockedClass mock) {
    String string = mock.data.asJson()
    def domain = new MyDomain(data: mock.data.asJson())
    domain.save()
}

When I step into this code with the debugger I can immediately see that the string has turned from {"content":"irrelevant"} in the string variable to "{\"content\":\"irrelevant\"}" in the domain variable.

It's only logical now, that in my test a comparison of the saved domain class string does not match the mocked input.

This is how MyDomain.data data looks when it's read from the database:

"\"\\\"{\\\\\\\"content\\\\\\\":\\\\\\\"irrelevant\\\\\\\"}\\\"\""

This is the same string parsed with new JsonSlurper().parseText(MyDomain.data):

"\"{\\\"content\\\":\\\"irrelevant\\\"}\""

Here's the mocked string parsed with JsonSlurper (as above):

[content:irrelevant]

Obviously the last example is what I expect. Can anybody tell me why Groovy/Grails adds a bulk load of crappy \\ to my simple and properly escaped string? I could even try a Groovy string '{"content":"irrelevant"}' but that doesn't make the slightest difference.

How can I perform unit test on my ES service?

I would like to perform unit tests on my service, that basically searches data in ES cluster using ES client. How to do this? Could anyone provide any example?

I found that I should use ESTestCase class but unfortunately documentation says literally nothing and also I cannot find any examples in the Internet - if there are examples there are rather for intergration testing in which I'm not interested about.

What use is @TestInstance annotation in JUnit5?

Could you give a simple explanation of @TestInstance annotation and how it could be useful in JUnit 5?

I think we can achieve the same effect probably by making our fields static.

How to send A/B testing fields in click stream events

I have a lot of production clickstream events and would like to do A/B testing on some of the features. Right now I sent each feature value in a separate column in my click stream events which I think is not right as the features for A/B testing are very volatile and continue to evolve\change\add. This leads to change in my schema and change in my tables which are created for click stream events

Is there a better way of doing this?

Rails controller integration test can't find model function

I have a controller integration test that creates a new User. As a result of the new User being created, I randomly assign a book to the User. First, I get a list of all available books from Book.get_all_books (a class method), but I am getting the error:

ActiveRecord::RecordNotFound: Couldn't find Book app/models/book.rb:15:in 'get_all_books'

I have prepared the database and it appears it loaded the data from the fixtures. When I launch the console in test mode, I can see the pre-seeded books.

jeudi 27 septembre 2018

Is there any way to find the elements in xcode UI testing, similar to that of appium?

I am new to xcode UI testing. I need to check whether an element appears on the screen and remains there for 5 secs. How can I do that?

Setting default url on Safari Launcher

When I run automation on appium on ios12 then browser default navigate to url (appium.io). And next navigate to URL that I had assigned. At this step, driver error appearance. How I can fix them. Have I can remove navigate to appium.io when run automation (setting on Safari Launcher app) or any soluton

(err_0038)Error Message:An unknown server-side error occurred while processing the command. Original error: Did not get any response after 300s

How to use docker-compose to restore fresh databases quickly for integration tests?

I would like to run integration and end-to-end tests with a database in a known state for each run, to make the tests independent and repeatable. An easy way of doing this is to use docker-compose to create a database container which loads the scheme and data from a dump file each time. However, this is far too slow to restore the database for every test.

A better way seems to be to restore the database once in a docker container or volume, and then copy (mount?) the container/volume database folder into the database container that the test will use, and have each test re-copy/mount the container/volume so that it is fresh.

However, I am not sure what the best way to do this with docker-compose is. Could anyone provide a minimal example or explanation as to how to do this?

Android, Espresso - Activity stops before whole test is finished when run as part of :app:connectedAndroidTest (runs fine in isolation)

I apologise if this is a bit too vague here, but I'm not allowed to post my whole actual code. All I can say is I have a problem running this test as a part of ./gradlew connectedAndroidTest

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MobileAppSanityTest extends AbstractEspressoTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule =
        new ClearPreferencesActivityTestRule<>(MainActivity.class, getFiles());

    @Override
    protected Context getContext() {
        return mActivityRule.getActivity();
    }

    @BeforeClass
    public static void beforeAll() {
        RoboGuice.Util.reset();
    }

    @Test
    public void test_SingleUserFlow() {
        navigateSplashScreen();
        logIn();
        doSomethingElse();
    }
}

What happens here is that when I run this test class on its own - it runs fine, but when I run it as a part of 'connectedAndroidTest' the activity is stopped right after 'navigateSplashScreen' and login cannot be performed.

Error I get is:

 java.lang.RuntimeException: No activities found. Did you t to launch the activity by calling getActivity() or startActivitySync or similar?

I'm quite new to Espresso and Android in general, so it's a bit hard to wrap my head around this. Please let me know if you need more information. I'll try to provide it out if that's the case.

Validate array within an array case with BDD karate

Using the karate bdd plugin for automated testing cases along with cucumber. Facing a trouble validating an api structure having an array list within an array. How to validate the valuesets array in array structure with bdd karate?

{
    "reqParam": "5bacfbaaa222ed1500f5aa7a",
    "selectionLimit": [],
    "valuesets": [
        [{
                "test": "sample",
                "testB": "sample"
            },
            {
                "test": "sample",
                "testB": "sample"
            },
            {
                "test": "sample",
                "testB": "sample"
            }
        ],
        [{
                "test": "sample",
                "testB": "sample"
            },
            {
                "test": "sample",
                "testB": "sample"
            }
        ]
    ]
}

Here is a piece of the code that I have been working on to accomplish this task.

* def samplePacket = { test: '#string', testB: '#string'}
Scenario: Check the valid params
        Given url API_URL
        Given path 'getParam/apicall'
        And params validParameter
        When method get
        Then status 200
        And match header Content-Type == 'application/json; charset=utf-8'
        #And print response.valuesets[0]
        Then match each response.valuesets == #[] samplePacket

Can't see .Net Core bitbucket pipelines test results

I finally managed to make reports of my tests in bitbucket pipeline by this command:

- dotnet test MyTests --logger "trx;LogFileName=test-reports/results.xml"

Build Teardown says:

Found matching test report file MyPath/test-reports/results.xml
Finished scanning for test reports. Found 1 test report files.
Merged test suites, total number tests is 0, with 0 failures and 0 errors.

However, I can't see these test results file in bitbucket. I know that there should be a new tab in pipeline window or something like it. Any suggestions how to see them in a nice display window?

Didn't find any documentation or articles.

Wildcard parameter when using "expects(x).with" in Mocha testing

I am using Mocha testing in a rails application and am attempting to test a method that takes 3 parameters. I want to verify that two of those parameters are what I expect however I don't care about what the third is.

Ex: Resque.expects(:enqueue).with(GithubLoggerJob,*,"Update: Updated Name")

I don't care what is passes into the spot where the asterix is. Is there any way to ignore that and just verify that GithubLoggerJob and Update: Updated Name are passed in? Thanks.

@Import vs @ContextConfiguration in SpringBoot application tests

Just find out that @Import annotation could be used in unit test of spring boot application to load configurations which are needed for the test. My question is about how correct this approach is. Is there some possible problems or traps here?

For now I found only one difference in behaviour. I have an abstract parent class for all tests with an internal @TestConfiguration static class in it with some common beans for testing. If I use @ContextConfiguration I should explicitly list it in the classes option of this annotation but with @Import it will be loaded automatically without explicit import. That the reason of such behaviour?

Mockito: Mock a method called in an other private class method

I have a service Class that I'm trying to test using Mockito, JUnit and JaCoCo. This class has some public method that uses other private method in the same class for some business logic : both of them (public and private) use DAO methods, that I usually mock while testing service layer. The problem is that while the DAO called from the public method return what I set in the test class, the DAO method from the private method called inside the public one return an empty value (an empty List in this particulare case). This is the service class:

@Service
public class EventService {

@Transactional(readOnly=true)
public List<ObjectDTO> publicMethod() {
                    List<Object> list = DAO1.call1();    // Not empty
                    return privateMethod(parameter);
}

private List<EventSummaryDTO> privateMethod() {
      List<Object> list = DAO2.call2();       // Empty
}

}

and this one is the test class:

public class ServiceTest extend AbstractTransactionalJUnit4SpringContextTests {

  @Mock
  private DAO1 mockDAO1;

  @Mock
  private DAO mockDAO2;

  @InjectMocks
  private Service service;

  @Test
  public void testcase() {

  Mockito.when(mockDAO1.call1()).thenReturn(list);
  Mockito.when(mockDAO2.call2()).thenReturn(list);

  List<ObjectDTO> list = service.publicMethod();
  list.size() // Empty

  }
}

How can I let the private method's call to return something different from nothing!?

Thanks in advance!

Can we create a "Problematic Tests" tab for a Teamcity build that execute functional tests?

I'm trying to add a new tab "Problematic Tests" (like Report Tab) on the Build menu (with Overview, change Log, Statistics,...) The build run tests on a remote machine then it display results on a Report tab. What i want to do is to have "Problematic Tests" for this build, so i will be able to see the failure rate of each executed test case.

The "Problematic Tests" is added automatically if we run nUnit tests, but in my case it's functional tests.

You can find here what i want to have Thanks,

I am not able to scroll horizontally using puppeteer. If anyone have any idea about horizontally scroll left to right or right to left

I am not able to scroll horizontally using puppeteer. If anyone have any idea about horizontally scroll left to right or right to left. I am trying to automate but i m stuck here.

horizontal scroll code!!

view of scroller

Unrelated warnings when testing Drupal 8

I have a simple module written for Drupal 8. It contains a dummy test, that I use to understand the basics of the framework.

<?php

namespace Drupal\loremipsum\Tests;

use Drupal\simpletest\WebTestBase;

class LoremIpsumTests extends WebTestBase {

  public static $modules = array('loremipsum');
  private $user;

  public function setUp() {
    parent::setUp();
    $this->user = $this->DrupalCreateUser(array(
      'administer site configuration',
      'generate lorem ipsum',
    ));
  }

  public function testDummy() {
    // Login.
    $this->drupalLogin($this->user);

    $this->assertTrue(true,"True is true");
  }
}

When running the tests through the admin GUI, the console spits out dozens of warnings that are not related at all to my module.

strpos() expects parameter 1 to be string, array given

strpos(Array, ':') (Line: 723)
Drupal\Core\Extension\ModuleHandler::parseDependency(Array) (Line: 228)
Drupal\Core\Extension\ModuleHandler->buildModuleDependencies(Array) (Line: 172)
Drupal\Core\Extension\ModuleExtensionList->doList() (Line: 274)
Drupal\Core\Extension\ExtensionList->getList() (Line: 1052)
system_rebuild_module_data() (Line: 1577)
install_profile_modules(Array) (Line: 638)
...

explode() expects parameter 2 to be string, array given

explode(':', Array) (Line: 724)
Drupal\Core\Extension\ModuleHandler::parseDependency(Array) (Line: 228)
Drupal\Core\Extension\ModuleHandler->buildModuleDependencies(Array) (Line: 172)
Drupal\Core\Extension\ModuleExtensionList->doList() (Line: 274)
Drupal\Core\Extension\ExtensionList->getList() (Line: 1052)
system_rebuild_module_data() (Line: 1577)
install_profile_modules(Array) (Line: 638)
...

I never use explode nor strpos anywhere in my module. When I test native modules from Drupal (like Logger for example) the warnings don't show up.

How can I trace where these error come from ? Is it possible it is from my YAML configurations ?

selenium unit testing is not working with simple usecase

I am a devloper who is trying to do some automation testing

I have choosen selenium-webdriver with mocha to achive it

I got sample as shown below

var webdriver = require('selenium-webdriver') // Added line
var By = require('selenium-webdriver').By,
    until = require('selenium-webdriver').until,
    chrome = require('selenium-webdriver/chrome'),
    test = require('selenium-webdriver/testing');

test.describe('Google Search', function() {
    var driver;

    test.before(function() {
        driver = new webdriver.Builder().forBrowser('chrome').build() // Changed line
    });

    test.after(function() {
        driver.quit();
    });

    test.it('should append query to title', function() {
        driver.get('http://www.google.com/ncr');
        driver.findElement(By.name('q')).sendKeys('webdriver');
        driver.findElement(By.name('btnG')).click();
        driver.wait(until.titleIs('webdriver - Google Search'), 1000);
    });
});

i have installed chrominum node and mocha

but when i do mocha filename

/home/dhanalakshmi/Desktop/seleniumm testing/test-project/spec.js:7 test.describe('Google Search', function() { ^

TypeError: test.describe is not a function at Object. (/home/dhanalakshmi/Desktop/seleniumm testing/test-project/spec.js:7:6) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10)

i am getting the error as shown please say how to run the test case

How to test gateways containing exception filters in e2e testing

Problem

Exception filters does not seem to be used at all when doing E2E testing on a gateway

Code

some-gateway.e2e-spec.ts

import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';

import { AppModule } from '@/app.module';
import { SomeGateway } from './some.gateway';

describe('SomeGateway', () => {
    let app: INestApplication;
    let someGateway: SomeGateway;
    const mockClient = {
        emit: jest.fn(),
    };

    beforeAll(async () => {
        const moduleFixture = await Test.createTestingModule({
            imports: [AppModule],
        }).compile();

        app = moduleFixture.createNestApplication();
        await app.init();

        someGateway = app.get(SomeGateway);
    });

    afterAll(async () => {
        await app.close();
    });

    beforeEach(() => {
        jest.resetAllMocks();
    });

    describe('someEventListener', () => {
        it('does not throw an exception because I have a exception filter', async (done) => {

            await someGateway.someEventListener(
                mockClient
            );

            expect(mockClient.emit).toHaveBeenCalled();
            done();
        });
    });
});

some-gateway.ts

import { SomeExceptionFilter } from './some-exception-filter';
import { UseFilters } from '@nestjs/common';
import {
    SubscribeMessage,
    WebSocketGateway,
} from '@nestjs/websockets';

@UseFilters(new SomeExceptionFilter())
@WebSocketGateway({ namespace: 'robot-fleetbridge' })
export class SomeGateway {

    @SubscribeMessage('some-event')
    async someEventListener(client): Promise<void> {
        throw new Error();
    }
}

some-exception-filter.ts

import { ArgumentsHost, Catch } from '@nestjs/common';

@Catch()
export class SomeExceptionFilter {
    catch(exception: any, host: ArgumentsHost) {
        console.log('i should be called :(');

        const client = host.switchToWs().getClient();

        client.emit('exception', { message: 'not ok' });
    }
}

Some thoughts

maybe I should use app.getHttpServer() to be able to make it work, but how to simulate a socket.io connection using supertest?

Using jest-each for dynamic data testing

I working on React credit card input component.

I need to test credit card numbers by brand type using jest-each.

Existing code works but need to replace it with jest-each for dynamic data testing.

I think it needs to create an array and put inside my variables like visaNumber, mastercardNumber, amexNumber, expectedResult.

So how can i refactor in my case using jest-each?

Code:

import { mount } from 'enzyme';
import each from 'jest-each';
import * as React from 'react';
import { getCardTypeByValue } from '../../utils/formatter';
import CardNumber from './CardNumber';

const props = {
  placeholder: '',
  title: '',
};

// Valid Credit card numbers
const visaNumber = '4242 4242 4242 4242';
const mastercardNumber = '5555 5555 5555 4444';
const amexNumber = '3782 822463 10005';

function setup(ownProps = props) {
  return mount(<CardNumber {...ownProps} />);
}

describe('Card number component', () => {
  const wrapper = setup();

  it('Card number component should render properly', () => {
    expect(wrapper.instance() instanceof React.Component).toBe(true);
  });
});

describe('Get a card type by value', () => {
  it('Should get type for VISA', () => {
    const expectedResult = {
      maxCardNumberLength: 19,
      startPattern: /^4/,
      type: 'visa',
    };
    expect(getCardTypeByValue(visaNumber)).toEqual(expectedResult);
  });

  it('Should get type for MASTERCARD', () => {
    const expectedResult = {
      maxCardNumberLength: 16,
      startPattern: /^(5[1-5]|677189)|^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)/,
      type: 'mastercard',
    };
    expect(getCardTypeByValue(mastercardNumber)).toEqual(expectedResult);
  });

  it('Should get type for AMERICAN EXPRESS', () => {
    const expectedResult = {
      format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/,
      maxCardNumberLength: 15,
      startPattern: /^3[47]/,
      type: 'amex',
    };
    expect(getCardTypeByValue(amexNumber)).toEqual(expectedResult);
  });
});

Do I need Mocha if looks like pure JS is enough for me?

I am developing a WebExtension for browsers, and I want to start TDD. Usually, folks without experience in testing of client-side JS just google for a popular framework and stick with it - even without trying to test functions in pure JS. I do not like dependencies - I use anything only if I understand what problem it resolves, I like simplicity. Currently, I do not know why I need any Javascript unit-testing framework. Now I see at popular https://mochajs.org and do not see reasons to use it.

Now my code looks like this:

function unitTests() {  // eslint-disable-line no-unused-vars

(function _prepareRemoving_test() {
    (function _setUp() {
        _testUtils._fillDB();
    })();

    (async function _isUnique() {
        const {itemFeed, isUniqueForUser} = await _prepareRemoving(_testUtils['id']);
        console.assert(itemFeed['hashArticle'] === _testUtils['val']['hashArticle'], itemFeed);
        console.assert(isUniqueForUser === true, isUniqueForUser);
    })();
    _testUtils._addArticleWithDuplicatedHash();
    (async function _isNotUniqueWhenPreviousWithTheSameHash() {
        const {itemFeed, isUniqueForUser} = await _prepareRemoving(_testUtils['id3']);
        console.assert(itemFeed['hashArticle'] === _testUtils['val3']['hashArticle'], itemFeed);
        console.assert(isUniqueForUser === false, isUniqueForUser);
    })();
    (async function _isNotUniqueWhenNextWithTheSameHash() {
        const {itemFeed, isUniqueForUser} = await _prepareRemoving(_testUtils['id2']);
        console.assert(itemFeed['hashArticle'] === _testUtils['val2']['hashArticle'], itemFeed);
        console.assert(isUniqueForUser === false, isUniqueForUser);
    })();

    (function _tearDown() {
        _testUtils._clearDB();
    })();

})();

(function _syncHistory_test() {
    // ===== setup =====
    const fetchOriginal = window.fetch;
    const chromeOriginal = window.chrome;
    // ===== end of setup =====

    (function _added() {
        (function _mock() {
            window.fetch = function() {
                _testUtils._mock(fetch, arguments);
                return fetchOriginal('unitTests/_syncHistory/mockResponses/added.json');
            };
            window._getArticle = function() {
                _testUtils._mock(_getArticle, arguments);
                return Promise.resolve();
            };
            window._persistItemFeed = function() {
                _testUtils._mock(_persistItemFeed, arguments);
            };
            chrome.runtime.sendMessage = function() {
                _testUtils._mock(chrome.runtime.sendMessage, arguments);
            };
            chrome.storage.sync.set = function() {
                _testUtils._mock(chrome.storage.sync.set, arguments);
            };
        })();

        _syncHistory(0, 'myFakeIdToken');

        console.assert(fetch['hasCalls'].length === 1);
        console.assert(fetch['hasCalls'][0][0] === `${stageUrlNew}history?updated=0`);
        console.assert(
            fetch['hasCalls'][0][1]['headers']['Authorization'] = 'myFakeIdToken'
        );

        setTimeout(_ => {  // setTimeout for waiting all callbacks from fetch()
            console.assert(_getArticle['hasCalls'].length === 1);
            console.assert(_getArticle['hasCalls'][0][0] === 1537886629);
            console.assert(
                _persistItemFeed['hasCalls'][0][0] === '1537886629'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][1] === 'https://example.com/favicon.ico'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][2] === 'https://example.com/my-article'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][3] === 'The title of article'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][4] === false
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][5] === true
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][6] === false
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][7] === '75042f43e7ba2228934f75d96a02f7a1'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][8] === 1
            );

            console.assert(chrome.runtime.sendMessage['hasCalls'].length === 1);
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['fromPopup'] === '_cacheSynced'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['hashArticle'] ===
                    '75042f43e7ba2228934f75d96a02f7a1'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['id'] === '1537886629'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['lenChunks'] === '1'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['idToken'] === 'myFakeIdToken'
            );

            console.assert(
                chrome.storage.sync.set['hasCalls'].length === 1
            );
            console.assert(
                typeof chrome.storage.sync.set['hasCalls'][0][0]['updated'] === 'number'
            );
            console.assert(
                Number.isInteger(chrome.storage.sync.set['hasCalls'][0][0]['updated'])
            );
            console.assert(
                (chrome.storage.sync.set['hasCalls'][0][0]['updated'] + '').length === 10
            );

            _syncHistory(1537886629, 'myFakeIdToken');
            console.assert(fetch['hasCalls'].length === 2);
            console.assert(
                fetch['hasCalls'][1][0] === `${stageUrlNew}history?updated=1537886629`
            );
            console.assert(
                fetch['hasCalls'][1][1]['headers']['Authorization'] = 'myFakeIdToken'
            );

            (function _tearDown() {
                window.fetch = fetchOriginal;
                window.chrome = chromeOriginal;
            })();

        }, 100);
    })();
}

My helper function:

const _testUtils = {  // eslint-disable-line no-unused-vars
    id:  1000000,
    id1: 1111111,
    id2: 2222222,
    id3: 3333333,
    val:  {'hashArticle': '75042f43e7ba2228934f75d96a02f7a0', 'cache': [new Blob(), new Blob()]},
    val1: {'hashArticle': '75042f43e7ba2228934f75d96a02f7a1', 'cache': [new Blob(), new Blob()]},
    val2: {'hashArticle': '75042f43e7ba2228934f75d96a02f7a2', 'cache': [new Blob(), new Blob()]},
    val3: {'hashArticle': '75042f43e7ba2228934f75d96a02f7a2', 'cache': [new Blob(), new Blob()]},

    _fillDB: function() {
        return Promise.all([
            _insertOrReplace(this.id,  this.val),
            _insertOrReplace(this.id1, this.val1),
            _insertOrReplace(this.id2, this.val2)
        ]);
    },
    _addArticleWithDuplicatedHash: function() {
        _insertOrReplace(this.id3, this.val3);
    },
    _clearDB: function() {
        _deleteArticle(this.id);
        _deleteArticle(this.id1);
        _deleteArticle(this.id2);
        _deleteArticle(this.id3);
    },
    _hasCallsify: function(obj) {
        if (!obj['hasCalls']) {
            obj['hasCalls'] = [];
        }
    },
    _mock: function(obj, _arguments) {
        this._hasCallsify(obj);
        obj['hasCalls'].push(_arguments);
    }
};

Spring Boot 2.0 Integration Test for JmsTemplate

I have a very simple MessageHandler class that thanks to Spring Boot works at runtime with just the following lines of code and config:

msg handler

@Component
public class MessageHandler {

    @JmsListener(destination = "${solace.jms.queueName}")
    public void processMsg(Message msg) {
        MessageHeaders hdrs = msg.getHeaders();
        etc...

main class

@SpringBootApplication
public class Application implements CommandLineRunner {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

config

solace.jms.client-name=eeeee
solace.jms.client-password=dddd
solace.jms.client-username=ccccc
solace.jms.msg-vpn=bbbb
solace.jms.host=smf://aaaaa.xx.yy.com:8000
solace.jms.queueName=ffffff

What I'm looking for now is how to test this at compile time. Specific questions I have are how to Autowire the JmsTemplate as a mocked instance and what configuration values I should use in the test app properties.

Thanks

Separate tests in groovy

I want separate some maven tests in groovy and i have this syntax:

stash includes: 'Tests/**', name: "tests"
stash includes: 'p2/blabla/site/**', name: "extensions_p2"
stash includes: 'Maven/blavlavla/**', name: "extensions_maven"

I'm at the beging with this programing language and i dont understande it very well...

Those are the test in mave to separete in groovy

<id>machine</id>
<modules>
    <module>../test1</module>
    <module>../test2</module>
    <module>../test3</module>
</modules>  

And what does that mean stash/unstash ?

Please some advices

Testing API with Swagger/OAS

I've spent some time documenting an API with Swagger/OAS 3. I want to validate our current API conforms with the OAS 3 document. How can I do this?

No tests found in long file path name VSTest

I run a CI pipeline on jenkins with VSTest running our Unit Tests and Integ Tests, the machine is Winodws Server 2016 and we have enabled the long filepath option in the registry.. My question is has VSTest taken advantage of this long file path api given by MS as I have ran into issues where the tests cannot be found due to the file adapter path being too long, thus not discovered by VSTest console..

The tests will then become available if I use a temporary custom workspace and rerun.. Any help on this would be great

Creating a generic UI in React that wraps UI library

I will give a real-life example to give an idea of the problem I am trying to solve.

My team was responsible for a React app that was built with Semantic UI as its UI library. Here is a list of tests that were written (note we have our own definition for test types)

  • Unit Tests: test per component using Enzyme.
  • System Tests: done mainly on container components. Enzyme and sinon and fetch-mock where used for mocking.
  • End to end tests: Done with puppeteer.

Later on, our product managers wanted a Manerial UI based theme. To make it possible we need to

  1. Replace semantic UI components with Material UI components
  2. Write new test helpers for our system & unit. Then update all our tests to use the new test helpers
  3. Write new helpers for out End to End tests.

It was a painful process to make it possible, and it is still partially done. I thought that one of our mistakes were not defining components that are more generic and wrap our UI logic. However, after reviewing component API of both Semantic UI and Material UI I m wondering if this was even possible. Since:

  1. Each Library has different implementation of the component
  2. Components have different attributes
  3. HTML structure is different so End to End test still need to be changed when UI Library is swapped.

Now my question: Has anyone faced the same issues and how did you tackle this problem?

Uncaught Error: Uncaught (in promise): Error: Cannot match any routes

First, sorry for my bad english :)

I started the code for just 6 month on React and now on Angular.

I'm going to build a SPA with Angular 6 in front and NodeJS in back. It's not already done, but I want to check and to start the unit test. It's the first time i'm doing this. (I'm just begin with Angular 1 month ago).

I'haven't code the tests yet, but juste configure them (imports the module, the providers, the reactformModule, browserAnimationModule, ngFormModule, etc...) Everything is ok and all the tests are ok except juste one. In dev mode (with npm start), my SPA is working without any probleme and without any warning in my brower's console

BUT, when I'm doing ng test, I have one probleme :

"[object ErrorEvent] thrown"

When I open the console, I have this error message :

"zone.js:813 Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'admin'"

You can see my console here !

I've already loooked for any solution on the web, but either it doesn't work, either I don't understant how I have to code the tests about the routing of my project.

Here my code :

package.json

    {
  "name": "front",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxyconfig.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.7",
    "@angular/cdk": "^6.4.7",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/material": "^6.4.7",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@ng-bootstrap/ng-bootstrap": "^3.0.0",
    "bootstrap": "^4.1.3",
    "core-js": "^2.5.4",
    "font-awesome": "^4.7.0",
    "rxjs": "^6.0.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.7.0",
    "@angular/cli": "~6.1.1",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "typescript": "~2.7.2"
  }
}

My app.module.ts

   import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { MatDialogModule, MatSnackBarModule, MatProgressBarModule } from '@angular/material';
import {MatCardModule} from '@angular/material';
import {NgbModule, NgbProgressbarModule} from '@ng-bootstrap/ng-bootstrap';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { MatIconModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatRippleModule,  MatFormFieldControl } from '@angular/material';




import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { BestiaireComponent } from './api/bestiaire/bestiaire.component';
import { VegetalComponent } from './api/vegetal/vegetal.component';
import { DecoComponent } from './api/deco/deco.component';
import { FicheBestiaireComponent } from './fiche-bestiaire/fiche-bestiaire.component';
import { formAdminComponent } from './admin/form-admin/formAdmin.component';
import { PageAdminComponent } from './admin/page-admin/page-admin.component';
import { FormBestiaireComponent } from './admin/form-bestiaire/form-bestiaire.component';
import { ColumnArtisanatComponent } from './home/column-artisanat/column-artisanat.component';
import { MenuComponent } from './home/menu/menu.component';
import { CarouselComponent } from './home/carousel/carousel.component';
import { CardMurielComponent } from './home/card-muriel/card-muriel.component';
import { FormContactComponent } from './home/form-contact/form-contact.component';
import { ModalFicheComponent } from './fiche-bestiaire/modal-fiche/modal-fiche.component';
import { ModalVegetalComponent } from './modal-vegetal/modal-vegetal.component';
import { FormVegetalComponent } from './admin/form-vegetal/form-vegetal.component';
import { NewUserComponent } from './admin/new-user/new-user.component';
import { ForgotPasswordComponent } from './admin/forgot-password/forgot-password.component';
import { UpdatePasswordComponent } from './admin/update-password/update-password.component';
import { FooterComponent } from './footer/footer.component';
import { SearchBarComponent } from './search-bar/search-bar.component';
import { ResultSearchComponent } from './result-search/result-search.component';
import { NavbarMobileComponent } from './navbar-mobile/navbar-mobile.component';




const appRoutes : Routes = [ 
  {path : 'bestiaire', component : BestiaireComponent}, 
  {path : 'bestiaire/:id', component : FicheBestiaireComponent},
  {path : 'vegetal', component : VegetalComponent},
  {path : 'deco', component : DecoComponent},
  {path : 'auth', component : formAdminComponent},
  {path : 'admin', component : PageAdminComponent },
  {path : 'admin/newuser', component : NewUserComponent},
  {path : 'auth/forgotPassword', component : ForgotPasswordComponent},
  {path : 'auth/:token/updatePassword', component : UpdatePasswordComponent},
  {path : 'search', component : ResultSearchComponent}, 
  {path : '', redirectTo:'/', pathMatch:'full'}, 
  {path : '**', redirectTo:'/'}


]

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    BestiaireComponent,
    VegetalComponent,
    DecoComponent,
    FicheBestiaireComponent,
    formAdminComponent,
    PageAdminComponent,
    FormBestiaireComponent,
    ColumnArtisanatComponent,
    MenuComponent,
    CarouselComponent,
    CardMurielComponent,
    FormContactComponent,
    ModalFicheComponent,
    ModalVegetalComponent,
    FormVegetalComponent,
    NewUserComponent,
    ForgotPasswordComponent,
    UpdatePasswordComponent,
    FooterComponent,
    SearchBarComponent,
    ResultSearchComponent,
    NavbarMobileComponent,
    ],

  imports: [
  BrowserModule,
  HttpClientModule,
  FormsModule,
  MatDialogModule,
  MatCardModule,
  MatButtonModule,
  MatFormFieldModule,
  MatInputModule,
  BrowserAnimationsModule,
  NgbModule,
  ReactiveFormsModule,
  MatIconModule,
  MatSnackBarModule,
  MatProgressBarModule,
  NgbProgressbarModule,
  RouterModule.forRoot(appRoutes)
  ],
  entryComponents:[
    FormBestiaireComponent,
    ModalFicheComponent,
    ModalVegetalComponent,
    FormVegetalComponent,
    SearchBarComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

How I'm suppose to code the tests about the routing in order to dissmiss this error message. I really apreciate if someone could help me in details because, even thanks to the docs on the web, i can't fix it. I don't know where I suppose to look for, which component ? AppModule ? Each component where I use Router (from Angular).

I'v not build my project yet, but I suppose i'll have the same error, so I would like to fix it before building.

Thanks !

hollowspy

mercredi 26 septembre 2018

Jenkins bi-weekly build

How to setup jenkins job to only run biweekly at 8 AM in the morning.

Considering only the working days, Monday through Friday.

Basically running the build every second Friday.

How to create a race condition in C++

I want to test some Object's function for thread safety in a race condition. In order to test this I would like to call a function simultaneously from two (or more) different threads. How can I write code that guarantee that the function calls will occur at the same time or at least close enough that it will have the desired effect?

CMake: target "test" doesn't build tests, target "all" does

I created a command-line portable script-based industrialized agnostic build system useful to quickly build several dependent projects while not having to rely on a particular IDE or a build factory. It's agnostic, because it's not based on a single build engine. I founded the first version using cmake, because my projects are mostly C++, but that'll evolve (to include gradle for example or whatever). That's to say, I'm not centered on CMake, it's merely a tool to a goal, easy portable C++ project building. I had BJam in mind formerly and would have kept it if there had been more documentation.

As a result though, I'm very dependent on CMake to perform the build and unit tests. As of today, I realized that tests are built under the 'all' target and run under the 'test' target.

With CMake 2- (and -here for example- a Unix Makefiles generator):

make all  # Build project AND tests
make test # Run tests

With CMake 3+ and any generator:

cmake --build . --target all  # Build project AND tests
cmake --build . --target test # Run tests

I'd like to know if someone would know a way to split the 'build project' phase apart from the 'build tests' phase (also because it's feels more natural in my build system to join test building and running tests than the other way around).

Important precision: I don't want to bootstrap the project with one vision or another (by flipping BUILD_TESTING). The idea would be to have 3 stages like:

cmake --build . --target <project>     # 1. Build project only
cmake --build . --target <build_tests> # 2. Build tests
cmake --build . --target <run_tests>   # 3. Run tests

If I choose not to run tests, I could go straight from phase 1 above to installing, but running phase 3 would trigger the previous dependent phases.

Any clue? (If not, I suspect I'll have to ask CMake developers directly...)

Thanks in advance. Regards.

What does this statement mean "Cypress commands do not return their subjects, they yield them"?

I'm learning about Cypress.io and came across this statement in their official site Cypress.io

"Cypress commands do not return their subjects, they yield them."

What is the difference between "yield" and "return" in commands in cypress.io?

JavaScript Jasmine Framework how to write a Test to Fail case

I have done testing of software with 'Test to pass' cases and 'Test to fail'. Test to fail cases are very important for developing good software as that is where most of the bugs come from. I am wondering how I can write these kinds of unit tests using the Jasmine framework?

Example of a Test to Pass:

it('should set position to true', () => {
  spyOn(service, 'SetPositionAsPositive');
  service.SetPositionAsPositive();
  expect(service.position).toEqual(true);
});

Not A proper Test to Fail case would be something like this:

it('should not set position to false', () => {
  spyOn(service, 'SetPositionAsPositive');
  service.SetPositionAsPositive();
  expect(service.position).toEqual(false);
});

However as expected this fails my test case instead of passing which is correct. But I would like the test case to expect to fail not to pass. So a pass would be failure for these kinds of test cases.

The best I have come up with is this below however I think this still counts as a test to pass?

it('should not set position to false', () => {
  spyOn(service, 'SetPositionAsPositive');
  service.SetPositionAsPositive();
  expect(service.position).not.toEqual(false);
});

How to know the current url when using MemoryRouter

I'm trying to figure out how to use a test to assert what the current location pathname is.

As an experiment I wrote the following test

test(Can navigate MemoryRouter, (done) => { const logAll = (p, ...args) => { console.log(SOME OUTPUT,p, ...args) return p.location.pathname }

const div = document.createElement('div')

const Test = () => (
  <MemoryRouter>
    <React.Fragment>
      <Link to="/foo/bar" id="click-me" />
      <Route render={logAll} />
    </React.Fragment>
  </MemoryRouter>
)
ReactDOM.render(React.createElement(Test), div)
console.log('click')
Simulate.click(div.querySelector('#click-me'))

})

I would expect because the logAll route matches all changes for it to log once at / (which it does) and then again at /foo/bar. But the latter never logs before the test times out (about 5 seconds).

What am I missing?

Forcing input of an element through Java Script and Robot Framework

I'm trying to test a checkout page that contains credit card details. I'm using Robot FrameWork in pycharm to write automation scripts. A simple ; Input text Xpath doesn't really work

The error that I get is something like this in the log file that's generated after I run my automation script.

KEYWORD Selenium2Library . Capture Page Screenshot 11:24:11.934 INFO Typing text '4111 1111 1111 1111' into text field 'id=card-number-element'. 11:24:12.294 FAIL InvalidElementStateException: Message: invalid element state: Element must be user-editable in order to clear it. (Session info: chrome=69.0.3497.100) (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.17134 x86_64)

SO, I thought an alternative approach would be to inject the card number using JAVA Script. May I know how I can be able to do that? Execute Javascript document.evaluate(' ${loc_credit_card_num}', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).value = "4111 1111 1111 1111" This is what I thought was the right way, but doesn't really work

Jasmine: toHaveBeenCalled() returns undefined

As far as I understand, the .toHaveBeenCalled() Matcher of jasmine returns a Promise which is resolved when the function has been called. Actually for me, it returns undefined:

it('should show the first entries', () => {
  expect(contentfulService.first)
    .toHaveBeenCalled()
    .then(() => {
      expect(component.entries).toBe(entriesMock);
    });
});

The first method of the contentfulService is spied on like this:

contentfulService = TestBed.get(ContentfulService);
spyOn(contentfulService, 'first').and.callThrough();

The spec fails telling me:

TypeError: Cannot read property 'then' of undefined

I double checked it. It's definitely the result of toHaveBeenCalled() that returns undefined. Why? Am I getting something wrong?

PACT.io: Getting Missing requests error, when running npm run pactTest

enter image description here

Expected

Run npm run pactTest which will create a Pact file for my TotalPayout.test.pact.ts file.

Results

D, [#38238] DEBUG -- : {
  "description": "a GET request with a user id",
  "request": {
    "method": "GET",
    "path": "/frontoffice/api/liquidity-pool/get-total-payout",
    "headers": {
      "Accept": "application/json"
    }
  },
  "response": {
    "status": 200,
    "headers": {
      "Content-Type": "application/json"
    }
  }
}
W, [#38238]  WARN -- : Verifying - actual interactions do not match expected interactions. 
Missing requests:
  GET /frontoffice/api/liquidity-pool/get-total-payout


W, [#38238]  WARN -- : Missing requests:
  GET /frontoffice/api/liquidity-pool/get-total-payout

Here is my Pact File

// @ts-ignore
import path from 'path';
// @ts-ignore
import { Pact } from '@pact-foundation/pact';
import { getTotalPayout } from './LiquidityPool';

// const port = 12345;
const endpoint = '/frontoffice/api/liquidity-pool/get-total-payout';

const EXPECTED_BODY = {
  total_payout: 100.21,
};

const userId = 'foo';

describe('The API', () => {
  // Copy this block once per interaction under test
  describe('getUsersTotalPayout', () => {
    beforeEach(() => {
      const interaction = {
        uponReceiving: 'a GET request with a user id',
        withRequest: {
          method: 'GET',
          path: endpoint,
          headers: {
            Accept: 'application/json',
          },
        },
        willRespondWith: {
          status: 200,
          headers: {
            'Content-Type': 'application/json'
          },
          data: EXPECTED_BODY
        },
      };

      // @ts-ignore
      return provider.addInteraction(interaction);
    });
​
    // add expectations
    it('Should call getUsersTotalPayout and return an object with the total_payout', done => {
      getTotalPayout(userId)
        .then((response: any) => {
          console.log('response', response);
          console.log('EXPECTED_BODY', EXPECTED_BODY);
          expect(response).toEqual(EXPECTED_BODY);
        })
        .then(done);
    });
  });
});

Here is the service file that contains the getTotalPayout function:

This endpoint doesn't exist yet, but this Pact test should still work is my understanding.

// @TODO Note, this is the placeholder for LiquidityPool API endpoints
// @ts-ignore
import axios, * as others from 'axios';

const endpoint = '/frontoffice/api/liquidity-pool/';

export const getTotalPayout = async (userId: string) => {
  const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
  return response.data;
};

Also my axios mock in src/__mocks__/axios.ts

// tslint:disable-next-line:no-empty
const mockNoop = () => new Promise(() => {});

export default {
  get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 }})),
  default: mockNoop,
  post: mockNoop,
  put: mockNoop,
  delete: mockNoop,
  patch: mockNoop
};

Testing an isolated function of a component in React Jest

I am fairly new to Jest and Enzyme and I stumbled a cross a problem:

I have a Component which renders Children and also calls a method of those children. I achieve that by using refs. I call these functions something like:

somefunction = () => {
   this.myReference.current.childFunction();
   this.doSomethingOther();
}    

I now want to test the function somefunction. I want to check if the doSomethingOther function was called. Using a shallow render I cannot achieve that. The test would succeed if this.myReference.current.childFunction(); wasn't called. Jest cannot know it because it only renders shallow and therefore throws an error.

I may be missing the full understanding. I wonder if someone has a Idea to test this function without using mount.

Regards

Bob

PyTest Matplotlib Figure Appears on Show

I have a complicated method called plotter() which processes some data and produces a matplotlib plot with several components. Due to its complexity I simply want to test that the plot appears. This will confirm that all of the data is processed reasonably and that something gets shown without any errors being thrown. I am not looking to run an image comparison as that's not currently possible for this project.

My function is too complicated to show here, so the following example could be considered instead.

import matplotlib.pyplot as plt
import numpy as np

def plotter():
    x = np.arange(0,10)
    y = 2*x
    fig = plt.plot(x, y)
    plt.show()

Is there a way to use PyTest to simply assert that a figure appears? If not then solutions using other test frameworks would also be greatly appreciated.

(For context I am using Python 3.)

pintos 'alarm-multiple' test stops suddenly

i'm doing pintos project 1 alarm clock.

To test it, make in pintos/src/threads/bulid and run pintos -v -- run alarm-multiple

I got my result

however, proper result is: proper result

In my case, it stopped after print "Execution of 'alarm-multiple' complete. ANYBODY KNOWS THE SOLUTION?? plz help

Java Eclipse Android testing - Tap doesn't work, imports are not recognized

I am trying to use TouchAction for testing Android Java Eclipse.

However, for some reason, Eclipse doesn't recognize tap and tapOptions.

In the following code:

package tests;

import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebElement;

import io.appium.java_client.TouchAction;
import static io.appium.java_client.touch.TapOptions.tapOptions;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import static java.time.Duration.ofSeconds;
import static io.appium.java_client.touch.offset.ElementOption.element;




public class gestures extends AppiumTest {

    public static void main(String[] args) throws MalformedURLException {
        // TODO Auto-generated method stub
        AndroidDriver<AndroidElement> driver=Capabilities();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElementByXPath("//android.widget.TextView[@text='Views']").click();
        //Tap
        TouchAction t =new TouchAction(driver);
        WebElement expandList=  driver.findElementByXPath("//android.widget.TextView[@text='Expandable Lists']");
        t.tap(tapOptions().withElement(element(expandList))).perform();
        driver.findElementByXPath("//android.widget.TextView[@text='1. Custom Adapter']").click();
    WebElement pn=  driver.findElementByXPath("//android.widget.TextView[@text='People Names']");

        t.longPress(longPressOptions().withElement(element(pn)).withDuration(ofSeconds(2))).release().perform();
        //Thread.sleep(2000);
        System.out.println(driver.findElementById("android:id/title").isDisplayed());

    }
}

, the following imports are not recognized:

import static io.appium.java_client.touch.TapOptions.tapOptions;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static io.appium.java_client.touch.offset.ElementOption.element;

Why they are not recognized?

I am using:

  1. Java JDK 1.8.0

  2. java client 5.0.0 beta 6 jar

  3. appium server v1.9.1

Laravel | Testing

I'm writing a http test for laravel 5.6. After test I've got a warnig "Test code or tested code did not (only) close its own output buffers".

In a tested method I have a Mail send method. I've figured out, z the error comes from this method.

The code of send email is

public static function onRequestPasswordChangeSendResetLink(User $user, $resetUrl)
{
        Mail::to($user->email)
            ->send(new PasswordChange($user, $resetUrl));
}

What is wrong?)

Pytest Tkinter Messagebox

My program generates an Alert / Message Box using the code below.

import tkinter as tk
from tkinter import messagebox

root = tk.Tk()
root.withdraw()
messagebox.showwarning('End of Data', "You have reached the end of the data.")

I want to run a simple unit test on this code. I want to assert that the message box appears and that the text in the message box is "You have reached the end of the data.". Perhaps something like assert appears and assert message == "You have reached the end of the data.".

Ideally I'd like to do this using PyTest, however solutions using other frameworks would still be greatly appreciated.

(For context I am using Python 3.)

Soft assertions in javascript

I have two backend projects P1 & P2. Data from P1 has to flow into P2 after some processing via a middleware. I am writing this middleware and I have to create an E2E testing module.

I will have 100s of test cases and in each there may be 3 or 4 expect statements. The chai 'expect' function is a form of hard assertion. How can I get soft assertions in javascript. Basically, the test case will run all 3 or 4 expect statements and report which one's failed.

Routing Error in feature testing with RSpec

I'm working on a Project and trying to write some tests for it. At the Moment i'm doing the feature tests.
The Problem: I just can't use visit. Doesn't matter where i am using it. I receive the error: ActionController::RoutingError: No route matches [GET] "/".

Here is a simple example of the test:
require 'rails_helper'

RSpec.feature "Welcome", type: :feature do
  context 'sign in user and load index' do
    visit new_user_session_path  #didn't worked with "/" nor "/login" either
  end
end

May it's a problem with RSpec? I just don't know how to fix it.

I'm really glad if someone would try to help me.

Jest unresolved promise do not fail

Jest docs says:

Unresolved Promises

If a promise doesn't resolve at all, this error might be thrown:

(and so on)

In my case this not happen. I have this test:

test('detect infinite loop', () => {
    expect.assertions(1);

    const vastPromise = VastUtils.parseFromUrl(infiniteLoopUrl);
    const expectedError =
        new VastError(VastErrorCodes.WRAPPER_LIMIT_REACHED);
   return expect(vastPromise).rejects.toEqual(expectedError); 
});

VastUtils simply fetch an XML located at infiniteLoopUrl, parse it, and if this xml point to another xml, VastUtils follow the link, parse the new xml, merge them and repeat the process. Now, infiniteLoopUrl point to an XML that refers itself, so it is an infinite loop. "correctly", the code follow xml link infinitely, and never resolve or reject the promise.

I expect above test fail after a certain timeout, but it didn't.

Someone can help me? Thanks