lundi 30 avril 2018

How can I supply a cookie in a Scalatra test request?

I have a Scalatra controller method that reads and sets some cookies. It looks something like this:

get("/cookietest") {
  cookies.get("testcookie") match {
    case Some(value) =>
      cookies.update("testcookie",s"pong:$value")
      cookies.set("testcookie_set", "0")
      Ok(value)
    case None =>
      BadRequest("No cookie")
  }
}

I cannot seem to find a way to send cookies with the request in the test method:

// I want to do something like this:
test("GET / on DownloadsServlet should return status 200"){
  request.setCookies("testcookie", "wtf")
  get("/cookietest"){
    cookies("testcookie") should equal ("pong:wtf")
    cookies("testcookie_set") should equal ("0")
    status should equal (HttpStatus.OK_200)
  }
}

There is no request or cookies in scope, though.

How to classify tests according to test sizes in JUnit

Given I have test sizes: small, medium and large as described in https://testing.googleblog.com/2010/12/test-sizes.html.

How can I classify all my tests according to test sizes?

What are the differences between static binary instrumentation and the dynamic binary instrumentation?

I was wondering what would be the differences between static and dynamic binary instrumentation. I have used tools like Valgrind but I know for sure that it is a static analysis tool :) can someone explain the differences between static and dynamic binary instrumentation? thanks in advance :)

Firefox wont display files stored locally on computer (Like images, css stylesheets)

I am trying to test my code for a website that I have stored on my computer (opening the .html files that i have saved on my computer in firefox) and when I view it in firefox, firefox does not display any pictures, stylesheets. I think this means firefox cannot find the files stored on my computer??? I refer to the the right way, and chrome, edge, ie, will work fine! Please let me know if ive not been clear enough. im sure im doing something wrong so please help! im just learning so its kind of hard for me to figure out what i need to do!

Thanks!

Mock Retrofit error okhttp3.ResponseBody$1 cannot be cast

I'm trying to test a snippet of my code that uses retrofit, so I've created an interface to "mock" the return, it works in parts, it can invoke the onresponse of enqueue, however it can not convert Response <AuthResponse> response, follows the error:

java.lang.ClassCastException: okhttp3.ResponseBody$1 cannot be cast to br.com.safety.safetyrecognitionsdk.data.network.auth.AuthResponse

interface to mock

public interface AuthRepositoryBoundary {

    Call<AuthResponse> auth(String appKey, String projectId);

}

Class mocked

public class AuthSuccessTest implements AuthRepositoryBoundary {

    @Override
    public Call<AuthResponse> auth(String appKey, String projectId) {

        ResponseBody body = ResponseBody.create(
                MediaType.parse("application/json"),
                MockAuth.AUTH_SUCCESS
        );

        Response aResponse = Response.success(body, new okhttp3.Response.Builder() //
                .code(201)
                .message("OK")
                .body(body)
                .protocol(Protocol.HTTP_1_1)
                .request(new Request.Builder().url("http://localhost/").build())
                .build());

        return Calls.response(aResponse);
    }

}

implementation

@Override
public void auth(String appKey, String projectID) {
     this.authRepository.auth(appKey, projectID).enqueue(new Callback<AuthResponse>() {
          @Override
          public void onResponse(Call<AuthResponse> call, Response<AuthResponse> response) {
              switch (response.code()) {
                  case 201:
                      authListener.onSuccess(response.body());
                      break;
                  case 401:
                      authListener.onUnauthorized("Unauthorized");
                      break;
                  default:
                      authListener.onError("Server error");
                      break;
              }
         }

          @Override
          public void onFailure(Call<AuthResponse> call, Throwable t) {
              authListener.onError(t.getMessage());
            }
        });
    }

The test:

   @Test
    public void when_success_authentication_should_be_invoke_on_success() {
        this.authListenerMock = mock(AuthListener.class);
        this.authRepositoryMock = mock(AuthRepositoryBoundary.class);

        this.authSuccessTest = new AuthSuccessTest();

        this.safetyRecognition = new SafetyRecognition()
                .setCredentials("project_id", "key_id")
                .auth(new Authentication(this.authListenerMock, this.authSuccessTest));

        verify(this.authListenerMock).onSuccess(ArgumentMatchers.any(AuthResponse.class));
    }

component binding in angular 4,5

I have this in hello.component.ts I am getting some issues in the testing when I call service from component and checking data binding in component upon http request. below is the detail code. version angular 5.

import { Component, OnInit, Input, Inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpService } from '../http-service.service';
import { Constants } from '../constants';
@Component({
 selector: 'app-dashboard',
 templateUrl: './dashboard.component.html',
 styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private httpService: HttpService,
private location: Location,
public dialog: MatDialog
) { }
albumList = [];
photoList = [];
isDisabled = true;
selectedAlbumsHash = {};
dataSource = null;
displayedColumns = ['id', 'title'];
selectedAlbums = [];
ngOnInit(): void {
 this.route.params.subscribe(params => this.getAlbumDetails(params));    
}
getAlbumDetails(params) {
 let id = parseInt(params.id);
 this.httpService.get(Constants.ALBUM_URL).subscribe(
  data => {
    this.albumList = data.filter(
      (album) => {
       return album.userId === id;
      }
    );
   }
  );
 }
}

and in spec file

    import { TestBed, async,inject, fakeAsync, ComponentFixture } from '@angular/core/testing';
    import { DashboardComponent } from './dashboard.component'
    import { MatDialogModule, MatDialog, MatGridListModule, MatCheckbox } from '@angular/material';
    import { MatTableDataSource } from '@angular/material/table';
    import { TestsModule } from '../shared/modules/tests.module';
    import { Observable } from 'rxjs/Observable';
    import { ActivatedRoute, Params } from '@angular/router';
    import { HttpService } from '../http-service.service';
    import { Constants } from '../constants';
    import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
    import { HttpClientModule, HttpClient } from '@angular/common/http';
    import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
    import {
      RouterTestingModule
    } from '@angular/router/testing';
    describe('AppComponent', () => {
      let fixture;
      let app;
      let component;
      let data = [
        {
          "userId": 1,
          "id": 1,
          "title": "quidem molestiae enim"
        },
        {
          "userId": 1,
          "id": 2,
          "title": "sunt qui excepturi placeat culpa"
        },
        {
          "userId": 1,
          "id": 3,
          "title": "omnis laborum odio"
        },
        {
          "userId": 1,
          "id": 4,
          "title": "non esse culpa molestiae omnis sed optio"
        },
        {
          "userId": 1,
          "id": 5,
          "title": "eaque aut omnis a"
        },
        {
          "userId": 1,
          "id": 6,
          "title": "natus impedit quibusdam illo est"
        },
        {
          "userId": 1,
          "id": 7,
          "title": "quibusdam autem aliquid et et quia"
        },
        {
          "userId": 1,
          "id": 8,
          "title": "qui fuga est a eum"
        },
        {
          "userId": 1,
          "id": 9,
          "title": "saepe unde necessitatibus rem"
        },
        {
          "userId": 1,
          "id": 10,
          "title": "distinctio laborum qui"
        },
        {
          "userId": 2,
          "id": 11,
          "title": "quam nostrum impedit mollitia quod et dolor"
        },
        {
          "userId": 2,
          "id": 12,
          "title": "consequatur autem doloribus natus consectetur"
        }
      ];
      const two = 2;
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            DashboardComponent
          ],
          imports: [
            TestsModule,
            HttpClientModule,
            HttpClientTestingModule],
          providers: [
            { provide: MatDialog, useValue: { close: () => {} },
          },
          {
            provide: ActivatedRoute,
            useValue: {
              params: {
                subscribe: (fn: (value: Params) => void) => fn({
                    id: two,
                }),
            },
            },
        },
            HttpService
          ],
          schemas: [CUSTOM_ELEMENTS_SCHEMA] 
        }).compileComponents();
        fixture = TestBed.createComponent(DashboardComponent);
        component = fixture.debugElement.componentInstance;
      }));
      afterEach(inject([HttpTestingController], (backend: HttpTestingController) => {
        backend.verify();
      }));

      it('intialize', async(() => {
        let spy = spyOn(component, 'getAlbumDetails');
        component.ngOnInit();
        expect(spy).toHaveBeenCalled();
      }));
      it(`should return data`, async(inject([HttpService, HttpTestingController],
        (service: HttpService, backend: HttpTestingController) => {
          component.ngOnInit();
          service.get('https://jsonplaceholder.typicode.com/albums').subscribe(albumData => {
            expect(albumData.length).toEqual(100);
            expect(albumData).toEqual(data);
          });    
          const req = backend.expectOne('https://jsonplaceholder.typicode.com/albums');
          expect(req.request.method).toBe("GET");
          req.flush(data);
       })));
    });

everything is fine but only I get issues on below:

1. How to check this.albumList in spec file

I checked with spy also but it did not resolve problem.

Thanks

Laravel testing (sitemap xml page) ->get() returns blank xml

I'm trying to test a Laravel sitemap page.

Want to test that a uri 'sitemap/departments.xml' contains '/adhesives-sealants/adhesives/c657'

Here is my code:

    $response = $this->get( 'sitemap/departments.xml');

    $response->assertSee('/adhesives-sealants/adhesives/c657');

This is the response I get from test:

   Failed asserting that '' contains "/interior-exterior-pva-wood-glue/p31670".

When I dump out $response I get this:

<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  </urlset>

Which is not what is on the page!

Page looks like this:

xml

Where am i going wrong???

pytest mocking .count() and .find() functions of MongoReplicaSetClient object

I have a script called commons.py which contains some most commonly used functions.

In my main script, I am creating a mongo connection object:

db_ob = commons.db_connection()

db_connection returns a MongoReplicaSetClient connection object.

how to write test cases for my below function??

def check_entries():
    try:
        db_ob = commons.db_connection()
    except:
        print('Unable to connect to db!!')
        return False
    db_name = 'my_db_name'
    collection_name = 'my_collection_name'
    db_data = db_ob[db_name][collection_name].find()
    if db_data.count() == 0:
        print('No entries found in the collection!')
        return False
    return True

I can mock my db_connection function but I am having problem mocking the .count() and .find() functions.

Akka Stream test flow when Supervision.Resume implemented

I recently implemented an akka-stream flow which parse some json messages, validate the presence of a given key (destination_region) and pass to the next stage a case class containing the original message and the destination_region string.

I implemented a custom decider so that in case it face any parsing or key error, it will trigger Supervision.Resume after logging the exception.

A minimalistic implementation would look like:

package com.example.stages

import com.example.helpers.EitherHelpers._
/*
import scala.concurrent.Future
import scala.util.{Failure, Success, Try}

object EitherHelpers {
  implicit class ErrorEither[L <: Throwable, R](val either: Either[L, R]) extends AnyVal {
    def asFuture: Future[R] = either.fold(Future.failed, Future.successful)
    def asTry: Try[R]       = either.fold(Failure.apply, Success.apply)
  }
}
*/

import scala.concurrent.ExecutionContext

import akka.NotUsed
import akka.stream.scaladsl.Flow
import akka.stream.ActorAttributes.supervisionStrategy
import akka.stream.Supervision

import software.amazon.awssdk.services.sqs.model.Message

import io.circe.parser.parse
import io.circe.{DecodingFailure, ParsingFailure}


object MessageContentValidationFlow {
  def apply()(
      implicit executionContext: ExecutionContext): Flow[Message, MessageWithRegion, NotUsed] = {
    val customDecider: Supervision.Decider = {
      case e @ (_: DecodingFailure | _: ParsingFailure) => {
        println(e)
        Supervision.Resume
      }
      case _ => Supervision.Stop
    }
    Flow[Message]
      .mapAsync[MessageWithRegion](2) { message =>
        println(s"Received message: $message")
        val messageWithRegion = for {
          parsed <- parse(message.body()).asFuture
          region <- parsed.hcursor.downField("destination_region").as[String].asFuture
        } yield { MessageWithRegion(message, region) }
        messageWithRegion
      }
      .withAttributes(supervisionStrategy(customDecider))
  }
}

case class MessageWithRegion(message: Message, region: String)

I managed to test the case where the message is valid, however I have not clue about how to test the flow in case of ParsingFailure or DecodingFailure. I have tried almost all methods available for sub in the implementation below:

package com.example.stages

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Keep
import akka.stream.testkit.scaladsl.{TestSink, TestSource}
import io.circe.generic.JsonCodec, io.circe.syntax._
import io.circe.generic.auto._

import software.amazon.awssdk.services.sqs.model.Message
import org.scalatest.FlatSpec


@JsonCodec case class MessageBody(destination_region: String)

class MessageContentValidationFlowSpecs extends FlatSpec {
    implicit val system       = ActorSystem("MessageContentValidationFlow")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val (pub, sub) = TestSource.probe[Message]
        .via(MessageContentValidationFlow())
        .toMat(TestSink.probe[MessageWithRegion])(Keep.both)
        .run()

    "MessageContentValidationFlow" should "process valid messages" in {
        val validRegion = "eu-west-1"
        val msgBody = MessageBody(validRegion).asJson.toString()
        val validMessage = Message.builder().body(msgBody).build()

        sub.request(n = 1)
        pub.sendNext(validMessage)

        val expectedMessageWithRegion = MessageWithRegion(
          message = validMessage,
          region = validRegion
        )
        assert(sub.requestNext() == expectedMessageWithRegion)
    }

    ignore should "trigger Supervision.Resume with empty messages" in {
      val emptyMessage = Message.builder().body("").build()
      assert(emptyMessage.body() == "")

      sub.request(n = 1)
      pub.sendNext(emptyMessage)
      sub.expectComplete()
    }
}

Does anyone know how to test that Supervision.Resume was triggered and which exception was caught by the custom decider?

I want to use getters and setters for a game table

Hi Im trying to set up a person class for each player on a leaderboard, since i dont know how long the leader board is im going to try and loop the amount of people by the count of the rows in the leaderboard. Then im trying to "get" the points for each row and compare each one again the previous to assert the higher number is one the top, ive never used getters and setters before and cant seem to figure out how to do this, any help??

Here is the code for the information i want for each person, I need to find the player_picks, position and player_points . I then need to compare the count of each player_picks total with each player as i go down the leaderboard. If the pick_total is is equal i then need to compare their points total.Ive been trying this for a few weeks but someone suggested it would be easier making a player class and then using get and setters to assign attributes to each of them. SO i could then compare player1 with player 2, player 2 and player 3 etc. Whats making mit difficult is that i dont know the size of the list each time so its confusing me.

Below is the code im using which gives me the attributes im look to "set" but i dont know how to set up a "people" in a person class as the amount of people required each time with be changing (using int size) as a different amount of people join each game.

Im new to this so if im not explaining this well let me know.

public void test_player_leaderboard_entry() {

int size = playerRows.size();


for (int i = 0; i < size; i++) {

    //Position
    String position_first_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-position-value='" + i + "']")).getText();
    //Points
    String points_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-points-value='" + i + "']")).getText();
    //Username
    String username_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-player-value='" + i + "']")).getText();
    //Row Number
    Integer row = i + 1;
    Integer total_of_won_and_looking_good = 0;
    //PICKS
    for (int pick_number = 1; pick_number < 5; pick_number++) {
        String pick_status = Drivers.getDriver().findElement(By.xpath("//*[@id='root']/div/main/section[2]/section/div/ol/a[" + row + "]/li/div[3]/div[" + pick_number + "]/div")).getAttribute("data-qa-pick-state");
        //System.out.println(pick_status);
        if (Integer.parseInt(pick_status) == 2 || Integer.parseInt(pick_status) == 1) {
            total_of_won_and_looking_good = total_of_won_and_looking_good + 1;

        }
        //System.out.println(total_of_won_and_looking_good);
    }

    //System.out.println("On row number " + row + " we find " + username_player + " in position " + position_first_player + " with " + total_of_won_and_looking_good + " correct picks and " + points_player + " points!");
}

}

Protractor + Jasmine: Run same test in parallel with different data inputs

Wondering if there is a possibility to have a data driven tests with protractor + jasmine to execute it in parallel.

I have the following: storeList.json - an array with input params to test individual store. We have around 40 stores - records.

[
    {
     "storeId": "Store_ID_1",
     "storeController": "Store_Controller_1"
    },
    {
     "storeId": "Store_ID_2",
     "storeController": "Store_Controller_2"
    }
]

ordering.js - code (protractor) which takes each element from json above and executes it as separate test.

describe('Ordering', function () {

 all(require('../../assets/data/storeList'), (storeData) => {
    it(`Add all items with all modifiers to cart and checkout on ${storeData.storeId}`, async function () {

        let user = await userGenerator.Registered(storeData);
        await shoppingCartActions.fillCart(storeData,user);

        await homePageActions.openCart();

        await shoppingCartActions.validateCartMath();
        await shoppingCartActions.proceedToCheckout();

        await recommendedActions.continueToDeliveryOptions();

        await deliveryAndTipsActions.pickupAnd15PercentTip();
        await deliveryAndTipsActions.validateCartMath();
        await deliveryAndTipsActions.continueToAddressConfirmation();

        await pickupAddressConfirmationActions.continueToPaymentMethod();

        await paymentActions.fillCardData(storeData);

        await paymentActions.pay();
    });
});});

all.js - a snippet to make ordering.js a bit data driven

module.exports = (data, test) => {
const rows = Array.isArray(data) ? data : [data];

rows.forEach((row, index) => {
    test(row, index + 1)
})};

config.js

exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl : 'localhost',
restartBrowserBetweenTests: true,

maxSessions: 3,
multiCapabilities: [{
    'browserName': 'chrome'
}, {
    'browserName': 'chrome'
}, {
    'browserName': 'chrome'
}],

specs: ['./testsuite/ordering/*.js'],

allScriptsTimeout: 20000,
framework: 'jasmine2',
jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 600000,
    isVerbose: true,
},

onPrepare: () => {
    global.all = require('./all');
}};

Using this setup I get 3 instances of chrome running each executing ordering.js test with all available data inputs from storeList. So I get 6 tests executed, but in fact I'm willing 2 tests to be executed in parallel.

Another option I have tried is having multiple json for data input, and copies of ordering js, but that seems to be a bad practice.

Could someone point me to right direction having protractor data driven tests executed in parallel.

PHP unit test, mock entity and return null to throw exception?

The method which I need to test is:

getItemsByUserAccount(UserAccount $userAccount) {

    if (!$userAccount) {
        throw new \Exception('something went wrong');
    }

}

in my test I try to test it so:

testGetItemsByUserAccount() {

    $this->expectException(\Exception::class);

    $call = new ElementsController();
    $call->getItemsByUserAccount($userAccount)
}

The problem is, how to mock the Entity UserAccount and return null to get this exception?

I tried with $this->getMockBuilder(UserAccount::class), but I don't now how to return null here without method...

How can I test AWS Lambda functions locally?

Explain to me please what is the best way to locally test the lambda function. I used sam local and this solution https://github.com/lambci/docker-lambda for testing, but for example, where I invoke one lambda from another error occurs. In general, I can't make stubs for methods since lambda runs in a container

Contract tests or stubs for testing a relation between service controller-public client (feign)?

There is a Reporting service, that provides a feign client for public api. I want to choose better solution for testing a relation between that public client and service controller. What is better, to use contracts or stubs?

TestNG 6.10+ priority more important than preserve-order

I'm just working with some legacy code using TestNG framework in the 6.9.x version which I have to upgrade to the newer version of the framework - at least 6.11 . The problem is, many @Test annotations are marked with extra priorities attributes (@Test(priority = x)). But I've got a problem after change introduced in TestNG in the 6.10 release, namely:

New: Hierarchy on order features (from less important to more important): groupByInstance, preserveOrder, priority, dependsOnGroups, dependsOnMethods

Let's see an example of two test classes each containing three test methods with defined priorities:

First class:

public class TestClass1 {

    Logger LOG = Logger.getLogger("logger1");

    @Test(priority = 2)
    public void methodB() {
        LOG.info("Method 1B");
    }

    @Test(priority = 3)
    public void methodA() {
        LOG.info("Method 1A");
    }

    @Test(priority = 1)
    public void methodC() {
        LOG.info("Method 1C");
    }
}

The second one:

public class TestClass2 {

    Logger LOG = Logger.getLogger("logger2");

    @Test(priority = 1)
    public void methodC() {
        LOG.info("Method 2C");
    }

    @Test(priority = 2)
    public void methodB() {
        LOG.info("Method 2B");
    }

    @Test(priority = 3)
    public void methodA() {
        LOG.info("Method 2A");
    }

}

... and XML:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
  <test name="Test" preserve-order="true">
    <classes>
      <class name="com.test.radek.testngtest.TestClass2"/>
      <class name="com.test.radek.testngtest.TestClass1"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

After running such an XML suite, tests execution order is various for different TestNG releases:

For 6.9.x:

Apr 30, 2018 11:46:19 AM com.test.radek.testngtest.TestClass2 **methodC**
Apr 30, 2018 11:46:19 AM com.test.radek.testngtest.TestClass2 **methodB**
Apr 30, 2018 11:46:19 AM com.test.radek.testngtest.TestClass2 **methodA**
Apr 30, 2018 11:46:19 AM com.test.radek.testngtest.TestClass1 **methodC**
Apr 30, 2018 11:46:19 AM com.test.radek.testngtest.TestClass1 **methodB**
Apr 30, 2018 11:46:19 AM com.test.radek.testngtest.TestClass1 **methodA**

For 6.10 and higher:

Apr 30, 2018 11:47:37 AM com.test.radek.testngtest.TestClass2 **methodC**
Apr 30, 2018 11:47:37 AM com.test.radek.testngtest.TestClass1 **methodC**
Apr 30, 2018 11:47:37 AM com.test.radek.testngtest.TestClass2 **methodB**
Apr 30, 2018 11:47:37 AM com.test.radek.testngtest.TestClass1 **methodB**
Apr 30, 2018 11:47:37 AM com.test.radek.testngtest.TestClass2 **methodA**
Apr 30, 2018 11:47:37 AM com.test.radek.testngtest.TestClass1 **methodA**

So on these two example we can see that starting from TestNG 6.10 the preserve-order is completely ignored by priorities.

I saw a discussion regarding this preserve-order / priority correlation and now I'm no really sure how to handle this problem.

Main question:

Does TestNG have any mechanism which allows to execute tests according to priorities defined in @Test but grouped by a class (and the class order is defined in the XML suite) - so exactly as it was before TestNG 6.10 ?? What is the most correct way to migrate legacy tests relying on priorities and preserve-order to the new TestNG ?? Replacing the "priority" logic with dependsOnGroups could be very time-consuming for 1000+ test methods :/

Different parameters in TFS test with shared steps

Title: Different parameters in TFS test with shared steps.

I have a situation where I write a (manual) testcases in TFS (Server Version 15.117.27024.0)

I created a shared step with 2 parameter values. How do I call the same shared step, with different parameter values, from within the same testcase?

in pseudo-code:

test_case (
    shared_steps('param1','param2');
    shared_steps('param3','param4');
    step3();
    step4();
)

From the web interface, and various (old) blogpost, it seems like this is not possible, if that is indeed the case, I would like to have that verified.

Postman testscript - check that the status is NOT 200

I'm creating a script to test my api, I want to check that if the user doesn't enter the correct username & password, the access is denied.

I want my test to get PASS when the status is 401. But postman give me a FAIL because the status of my request is not 200.

I actually WANT my response to be 401 in order to pass the test.

Any idea on how to operate ?

Cheers

I tried using :

pm.test("Status code is 401", function () { pm.response.to.have.status(401); });

this test pass, but Postman give me a FAIL assertion on top :

fail

response is ok | AssertionError: expected response to have status code 200 but got 401

When use parameters in JSON POST data in Jmeter, another json entity is changed [duplicate]

This question already has an answer here:

i use JMeter for REST API testing and i have following request in my POST data section:

{
  "RootUrl": "http://localhost:4747",
  "Name": "E-commerce website",
  "ContentSite": true,
  "ContentLinks": [
    {
      "RegexPattern": "(log|sign)\\-?(out|off)"
    }
   ]
}

it is working regularly.

i'd like to use RootUrl as parameter so i created a "User Defined Variables". enter image description here

{
  "RootUrl": "${website_url}",
  "Name": "E-commerce website",
  "ContentSite": true,
  "ContentLinks": [
    {
      "RegexPattern": "(log|sign)\\-?(out|off)"
    }
   ]
}

When run it, it gives Request is NOT valid error. When i check it in Result tree, "RegexPattern" looks changed. There is one reverse slash in entity:

"RegexPattern": "(log|sign)-?(out|off)"

Do you have any idea why parameter does change another part?

Thanks in advance

dimanche 29 avril 2018

Getting the sequence of Gcov's executed lines information

I'm trying to get the sequence of line of code executed by a test case. By using Gcov, the output .gcov file shows which line of codes are executed and how many times they are executed but no information about the sequence.

The problem is that I can't get the sequence of the executed lines. Let's use this program as an example:

//...
for(i = 0; i < n; i++) {
    if(a > b) {
        // do something (line 10 - 15)
    } else {
        // do something (line 17 - 20)
    }
}
//...

For example with input x, the loop body will be iterated twice where the true branch of the if executed on the first iteration and then the false branch on the second iteration.

With Gcov, I can't get the information mentioned above because the .gcov file will only show that all the lines from both branch are executed. There is no way I can figure out the sequence whether line 10-15 or line 17-20 are executed first.

Is there a way of getting the sequence of executed lines with Gcov? Or is there any alternatives of doing this? Thank you

Subclassing TestCase in Python: Overwriting Field in Parent TestCase

I'm writing integration tests for an Alexa app.

Our application uses a controller-request-response pattern. The controller receives a request with a specified intent and session variables, routes the request to functions that do some computation with the session variables, and returns a response object with the results of that computation.

We get the right behavior from UnhandledIntentTestCase as far as test_for_smoke is concerned. However, test_returning_reprompt_text never fires, because returns_reprompt_text is never overwritten.

Can someone explain how I can overwrite it in the parent class and/or how the correct intent name is passed to the request object in setUpClass?

intent_base_case.py

import unittest

import mycity.intents.intent_constants as intent_constants
import mycity.mycity_controller as mcc
import mycity.mycity_request_data_model as req
import mycity.test.test_constants as test_constants




###############################################################################                                                                
# TestCase parent class for all intent TestCases, which are integration tests #                                                                
# to see if any changes in codebase have broken response-request model.       #                                                                
#                                                                             #                                                                
# NOTE: Assumes that address has already been set.                            #                                                                
###############################################################################                                                                

class IntentBaseCase(unittest.TestCase):

    __test__ = False

    intent_to_test = None
    returns_reprompt_text = False

    @classmethod
    def setUpClass(cls):
        cls.controller = mcc.MyCityController()
        cls.request = req.MyCityRequestDataModel()
        key = intent_constants.CURRENT_ADDRESS_KEY
        cls.request._session_attributes[key] = "46 Everdean St"
        cls.request.intent_name = cls.intent_to_test
        cls.response = cls.controller.on_intent(cls.request)

    @classmethod
    def tearDownClass(cls):
        cls.controller = None
        cls.request = None

    def test_for_smoke(self):
        self.assertNotIn("Uh oh", self.response.output_speech)
        self.assertNotIn("Error", self.response.output_speech)

    def test_correct_intent_card_title(self):
        self.assertEqual(self.intent_to_test, self.response.card_title)


    @unittest.skipIf(not returns_reprompt_text,
                     "{} shouldn't return a reprompt text".format(intent_to_test))
    def test_returning_reprompt_text(self):
        self.assertIsNotNone(self.response.reprompt_text)


    @unittest.skipIf(returns_reprompt_text,
                   "{} should return a reprompt text".format(intent_to_test))
    def test_returning_no_reprompt_text(self):
        self.assertIsNone(self.response.reprompt_text)

test_unhandled_intent.py

import mycity.test.intent_base_case as base_case


########################################                                                                                                       
# TestCase class for unhandled intents #                                                                                                       
########################################                                                                                                       


class UnhandledIntentTestCase(base_case.IntentBaseCase):

    __test__ = True

    intent_to_test = "UnhandledIntent"
    returns_reprompt_text = True

output

======================================================================
FAIL: test_correct_intent_card_title (mycity.test.test_unhandled_intent.UnhandledIntentTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/wdrew/projects/alexa_311/my_city/mycity/mycity/test/intent_base_case.py", line 44, in test_correct_intent_card_title
    self.assertEqual(self.intent_to_test, self.response.card_title)
AssertionError: 'UnhandledIntent' != 'Unhandled intent'
- UnhandledIntent
?          ^
+ Unhandled intent
?          ^^


======================================================================
FAIL: test_returning_no_reprompt_text (mycity.test.test_unhandled_intent.UnhandledIntentTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/wdrew/projects/alexa_311/my_city/mycity/mycity/test/intent_base_case.py", line 56, in test_returning_no_reprompt_text
    self.assertIsNone(self.response.reprompt_text)
AssertionError: 'So, what can I help you with today?' is not None

----------------------------------------------------------------------

Extending modules and testing class (or instance?) methods in Ruby

New to Ruby and thank you in advance! I have 2 files in the same directory. Where.rb =

module Where
  def self.where(hash = {})
    self.select do |fixture| #iterate over fixtures indexes |fixture| 
      hash.all?  do |key, value| #return true as long as hash exists
        value === fixture[key]
      end
    end
  end
end

and test.rb =

require 'minitest/autorun'
require './where.rb'

class WhereTest < Minitest::Test
  extend Where
  def setup
    @boris   = {:name => 'Boris The Blade', :quote => "Heavy is good. Heavy is reliable. If it doesn't work you can always hit them.", :title => 'Snatch', :rank => 4}
    @charles = {:name => 'Charles De Mar', :quote => 'Go that way, really fast. If something gets in your way, turn.', :title => 'Better Off Dead', :rank => 3}
    @wolf    = {:name => 'The Wolf', :quote => 'I think fast, I talk fast and I need you guys to act fast if you wanna get out of this', :title => 'Pulp Fiction', :rank => 4}
    @glen    = {:name => 'Glengarry Glen Ross', :quote => "Put. That coffee. Down. Coffee is for closers only.",  :title => "Blake", :rank => 5}

    @fixtures = [@boris, @charles, @wolf, @glen]
  end

  def test_where_with_exact_match
    assert_equal [@wolf], @fixtures.where(:name => 'The Wolf')
  end

  def test_where_with_partial_match
    assert_equal [@charles, @glen], @fixtures.where(:title => /^B.*/)
  end

  def test_where_with_mutliple_exact_results
    assert_equal [@boris, @wolf], @fixtures.where(:rank => 4)
  end

  def test_with_with_multiple_criteria
    assert_equal [@wolf], @fixtures.where(:rank => 4, :quote => /get/)
  end

  def test_with_chain_calls
    assert_equal [@charles], @fixtures.where(:quote => /if/i).where(:rank => 3)
  end
end

puts WhereTest

all my tests say NoMethodError: undefined method `where' for # Array:0x000000027d6a20.

I'm not sure what the error means. I created a module with a class method that should be usable. The module's method should be available to WhereTest class with extend Where

Does my program utilize any design patterns, and if so then which one?

So does my program utilize any design patterns and if so then which one? And also if it doesn't utilize any design patterns then how would I edit this to utilize a design pattern? I've just been trying to look at design patterns and got kind of confused by some of them. Here is an interface, an implement class and a main class.

public interface StackADTInterface<T>
{
    public void push(T element);

    public T pop() throws EmptyCollectionException;

    public T peek();

    public int size();

    public boolean isEmpty();

    public String toString();
}

public class StackArraySec02Imp<T> implements StackADTInterface<T>
{
    public final int maxLength = 100;
    public int top = 0;

    public T[] stackArray;

    public StackArraySec02Imp()
    {
        stackArray = (T[])(new Object[maxLength]);
    }

    public StackArraySec02Imp(int initialCapacity)
    {
        stackArray = (T[])(new Object[initialCapacity]);
    }

    @Override
    public void push(T element) 
    {
        if(size() == stackArray.length)
        {
            System.out.println("Stack is Full");
        }
        else
        {
        stackArray[top] = element;
        top++;
        }
    }

    @Override
    public T pop() throws EmptyCollectionException 
    {

        if(!isEmpty())
        {
            top--;
            T retObj;
            retObj = stackArray[top];
            stackArray[top] = null;
            return retObj;
        }
        else
        {
            throw new EmptyCollectionException("Stack is Empty");
        }
    }

    @Override
    public T peek() 
    {
        T retObj = stackArray[top-1];
        return retObj;
    }

    @Override
    public int size() 
    {
        return top;
    }

    @Override
    public boolean isEmpty() 
    {
        boolean isEmptyFlag = false;
        if(top <= 0 && stackArray[top] == null)
        {
            isEmptyFlag = true;
        }

        return isEmptyFlag;
    }

    @Override
    public String toString()
    {
        String result = "";

        for(int i = stackArray.length - 1; i >= 0; i--)
        {
            result += stackArray[i] + "\n";
        }

        return result;
    }

}


public class mainArraymain 
{
    public static void main(String[] args)
    {
        StackArrayImplemList<Integer> newStack = new 
        StackArrayImplemList<Integer>();


        newStack.push(12);
        newStack.push(5);
        newStack.push(6);
        newStack.push(7);
        newStack.push(8);
        newStack.push(9);

        System.out.println(newStack.toString());
    }

}

Jasmine test doesn't create a new instance of a class

I'm trying to apply a Jasmine test to my JS program (just a game) and it doesn't create new instances for some reason. Maybe some of you can help me find the error.

'use strict';


describe('logic(bingo)',function() {
    var bin
    beforeEach(function() {
        bin = new Bingo('Alex')
    })

    it('should throw error if name is not a string',function() {
        bin=new Bingo()
        expect(function() {
            return bin.name
        }).toThrowError('Input a string name')
    })

    it('should board.length===3 and board[0].length===5',function() {
        expect(bin.board.length).toBe(3)
        expect(bin.board[0].length).toBe(5)
    })
    }

bin doesn't store a "new Bingo". It keeps being undefined. This class Bingo is declared in a different file, the links are correct.

Thanks in advance.

Testing sessions laravel 5.* assertSessionHas('flash_notification.level', 'success')

i use laracasts/flash package for session messages, i want to test if it's work as it should be, i use those lines in my tests :

$response->assertRedirect('backend/brand'); // it works

$response->assertSessionHas('flash_notification.level', 'success'); // failure
$response->assertSessionHas('flash_notification.message', 'New post has been created.');

when running my tests, i get this failure message : Failed asserting that null matches expected 'success'.

any ideas/hints why the test failure?!

JUnit gives false when expected to be true

I'm testing a alphabetically sort method for a Linked List of "Request" objects called LstRequest, and when I test in JUnit, it gives me failure, but when I tested by me own, the same test gives me true.

This is the tested method:

public static LstRequest sort(LstRequest lstRequest, int param){
    for (int i=0; i<lstRequest.getSize()-1; i++){
        for (int j=1; j<lstRequest.getSize()-i; j++){
            if (lstRequest.getAt(j-1).compareOrder(lstRequest.getAt(j),param,0)){
                lstRequest.insertAt(j-1,lstRequest.getAt(j));
                lstRequest.removeAt(j+1);                               
            }
        }
    }
    return lstRequest;
}

and this is the method compareOrder() used in this method:

public boolean compareOrder(Request r, int param, int index){
    if (param==1){
        if (index!=this.source.length()){
                if (this.source.charAt(index)>r.source.charAt(index)){
                    return true;
                } else if (this.source.charAt(index)==r.source.charAt(index)){
                    return this.compareOrder(r,param,index+1);
                } else {
                    return false;
                }
        } else {
            return false;
        }
    } else if (param==2){
        if (index!=this.target.length()){
                if (this.target.charAt(index)>r.target.charAt(index)){
                    return true;
                } else if (this.target.charAt(index)==r.target.charAt(index)){
                    return this.compareOrder(r,param,index+1);
                } else {
                    return false;
                }
        } else {
            return false;
        }
    } else {
        if (index!=this.login.length()){
            if (this.login.charAt(index)>r.login.charAt(index)){
                    return true;
                } else if (this.login.charAt(index)==r.login.charAt(index)){
                    return this.compareOrder(r,param,index+1);
                } else {
                    return false;
                }
        } else {
            return false;
        }
    }
}

This is the JUnit test, it gives me the failure in the "Check by destination. " test:

public void testSort() {

    assertEquals("Check sort by user.", true, 
            SharingCar.sort(lst1, 3).equals(sorted1User));

    assertEquals("Check sort by origin.", true, 
            SharingCar.sort(lst1, 1).equals(sorted1Origin));

    assertEquals("Check sort by destination.", true, 
            SharingCar.sort(lst1, 2).equals(sorted1Destination));
}

And this are the Linked List used for the test:

    lst1.addLast(new Request("user1","Madrid","Barcelona"));
    lst1.addLast(new Request("user2","Alicante","Barcelona"));
    lst1.addLast(new Request("user3","Sevilla","Alicante"));
    lst1.addLast(new Request("user4","Valencia","Sevilla"));

    sorted1Destination.addLast(new Request("user3","Sevilla","Alicante"));
    sorted1Destination.addLast(new Request("user1","Madrid","Barcelona"));
    sorted1Destination.addLast(new Request("user2","Alicante","Barcelona"));
    sorted1Destination.addLast(new Request("user4","Valencia","Sevilla"));

I've done another class, for testing the same and looking where is the mistake, but the results are contradictory, this is the class:

public static void main(String[] args) {

    LstRequest lst1 = new LstRequest();
    lst1.addLast(new Request("user1","Madrid","Barcelona"));
    lst1.addLast(new Request("user2","Alicante","Barcelona"));
    lst1.addLast(new Request("user3","Sevilla","Alicante"));
    lst1.addLast(new Request("user4","Valencia","Sevilla"));

    LstRequest sorted1Destination = new LstRequest();
    sorted1Destination.addLast(new Request("user3","Sevilla","Alicante"));
    sorted1Destination.addLast(new Request("user1","Madrid","Barcelona"));
    sorted1Destination.addLast(new Request("user2","Alicante","Barcelona"));
    sorted1Destination.addLast(new Request("user4","Valencia","Sevilla"));

    SharingCar.sort(lst1,2).show();

    System.out.println(SharingCar.sort(lst1, 2).equals(sorted1Destination));

}

And this are the results given:

As you can see, the results are correctly alphabetically sorted by destination, and the same comparation, gives true, when in JUnit gives false.

Does anybody know why it gives false, or if is there a mistake?

Nunit: TestCaseSource is not waiting generate all test cases?

Hi everyone I have a problem with generate test cases for TestCaseSource. I wrote this code for tests:

using System;
using System.Collections.Generic;
using System.Linq;

using NUnit.Framework;

namespace HeapSort.Tests
{
    [TestFixture]
    public class Tests
    {
        [Test, TestCaseSource(typeof(TestsGenerator),"TestCases")]
        public void IsEqualCollections(int[] received, int[] expected)
        {
            CollectionAssert.AreEqual(received, expected);
        }
    }

    public class TestsGenerator
    {
        public static IEnumerable<TestCaseData> TestCases
        {
            get
            {
                for (var i = 0; i < 25; i++)
                {
                    int[] t1 = GenerateCollection(i), t2 = t1.ToArray();
                    HeapSort.Sort(t1);
                    Array.Sort(t2);

                    yield return new TestCaseData(t1, t2);
                }
            }
        }

        private static int[] GenerateCollection(int seed)
        {
            var rnd = new Random(seed+DateTime.Now.Millisecond);
            int size = rnd.Next(100, 10000); 
            int[] array = new int[size];
                for (var i = 0; i < size; i++)
                    array[i] = rnd.Next(-100, 100);
            return array;

//            return Enumerable
//                .Repeat(100, rnd.Next(100, 10000))
//                .Select(i => rnd.Next(-100, 100))
//                .ToArray();
        }
    }
}

Is there a problem? Instead of getting 25 tests I get from 1 to 8, and often at the initial point of testing it shows that the tests are 7/8, and at the end there is only one test case.

How i can solver it?

P.S. Sorry for my bad English.

Perhaps it is worth mentioning that I work on Ubuntu in Rider

What is a good test coverage percent for Javascript code?

I am working on a project with a very important front-end part. It is made with Javscript using JQuery for lots of things. We have also included some tests with Mocha. I don't know what rules (percentage) should be reasonable for code coverage in our tests.

As it has a lot of interactions with the DOM, and that cannot be unit tested, I just see impossible to achieve the highly recommended 80%. Not event a 50%. Is there any guidelines on what testing ratios are good for UI code?

Multiple arquillian based test files starts the context mutliple times

I have 2 test files

     @RunWith(Arquillian.class)
        public class Test_class_1{

            @Inject
            private Something something;

            @Deployment(name = "deployment_name", order = 1)
            public static WebArchive createInventory() {
                return AbstractArquillian.createWarFile("abcd.war",
                        "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar + "META-INF"
                                + File.separatorChar + "persistence-test.xml",
                        "META-INF" + File.separatorChar + "beans-test.xml");

            }

          @Test
          public void test_method () {
             ...
             ...
             ...
          }


    }


    @RunWith(Arquillian.class)
            public class Test_class_2{

                @Inject
                private Something something;

                @Deployment(name = "deployment_name", order = 1)
                public static WebArchive createInventory() {
                    return AbstractArquillian.createWarFile("abcd.war",
                            "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar + "META-INF"
                                    + File.separatorChar + "persistence-test.xml",
                            "META-INF" + File.separatorChar + "beans-test.xml");

                }


                @Test
                public void test_method () {
                   ...
                   ...
                   ...
                }

        }

There are 2 test files because test cases are logically different. But i want to start the context only once so that it takes less time. how should i modify it to achieve it? Spring integration test caches the context. isn't such thing available in arquillian.

samedi 28 avril 2018

Arquillian REST Testing Could not lookup value for field public java.net.URL

I am trying to test our REST Webservices with Arquillian.

I am new on Arquillian and I've never do testing before, i did a small tutorial and read the documentation and some other stuff and finally tried to write a simple test for my REST methode. But i am getting an exception saying:

java.lang.RuntimeException: Could not lookup value for field public java.net.URL ma.campus.services.ws.UtilisateurRestTest.deploymentURL

My Test Class:

import java.net.URL;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.extension.rest.client.ArquillianResteasyResource;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import ma.campus.entities.Utilisateur;
import ma.campus.services.UtilisateurService;
import ma.campus.services.ws.dto.UtilisateurDto;

@RunWith(Arquillian.class)
public class UtilisateurRestTest {

@ArquillianResource
public URL deploymentURL;

@Deployment(testable = false)
public static WebArchive create() {
        return ShrinkWrap.create(WebArchive.class).
                addClasses(Utilisateur.class,UtilisateurService.class,UtilisateurRest.class,UtilisateurDto.class);
}

@Inject
UtilisateurRest utilisateurRest;

@Test
@RunAsClient
@GET @Path("/utilisateur")
@Consumes(MediaType.APPLICATION_JSON) 
    public void listAllUtilisateurs(@ArquillianResteasyResource UtilisateurRest utilisateurRest) throws Exception{

    if(utilisateurRest!=null)
    {
        System.out.println("Not Null");
    ResponseEntity<List<UtilisateurDto>> response=utilisateurRest.listAllUtilisateurs();

   Assert.assertNotNull(response);

   Assert.assertNotEquals(new ResponseEntity<>(HttpStatus.NO_CONTENT),response);

   final List<Utilisateur> result = (List<Utilisateur>)response;

   Assert.assertNotNull(result);
   Assert.assertEquals(1, result.size());
    }else
        System.out.println("Null");     
}           
}

My pom.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
<groupId>ma.campus</groupId>
<artifactId>GestionDeParking</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>GestionDeParking</name>
<description></description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <!-- <version>1.4.5.RELEASE</version> -->
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.2.0.Final</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-solr</artifactId>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-core</artifactId>
        <version>1.13</version>
    </dependency>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>2.11.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

    <!-- test -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.spec</groupId>
        <artifactId>jboss-javaee-7.0</artifactId>
        <version>1.0.3.Final</version>
        <type>pom</type>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <version>1.2.0.Final</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.container</groupId>
        <artifactId>arquillian-weld-ee-embedded-1.1</artifactId>
        <version>1.0.0.CR9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.weld</groupId>
        <artifactId>weld-core</artifactId>
        <version>2.3.5.Final</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.6.4</version>
        <scope>test</scope>
    </dependency>
    <!-- for rest testing -->
    <dependency>
        <groupId>org.jboss.arquillian.extension</groupId>
        <artifactId>arquillian-rest-client-impl-jersey</artifactId>
        <version>1.0.0.Alpha3</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.arquillian.extension</groupId>
        <artifactId>arquillian-rest-client-impl-3x</artifactId>
        <version>1.0.0.Alpha3</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>2.2.1.GA</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <forkMode>perTest</forkMode>
                <skip>false</skip>
            </configuration>
        </plugin>
    </plugins>
</build>

My REST Service:

@RestController
public class UtilisateurRest {
    public static final Logger logger = LoggerFactory.getLogger(UtilisateurRest.class);
@Autowired
private UtilisateurService utilisateurService;

@Autowired
private PasswordEncoderService passwordEncoderService;

// ------------------- All Users---------------------------------
@Secured(value={"ROLE_1"})
@RequestMapping(value = "/utilisateur", method = RequestMethod.GET)
public ResponseEntity<List<UtilisateurDto>> listAllUtilisateurs() {
    List<Utilisateur> listUtilisateur = utilisateurService.findAllUtilisateurs();

List<UtilisateurDto> listUtilisateurDto = new ArrayList<>(listUtilisateur.size());


    for (Utilisateur utilisateur : listUtilisateur) {
        listUtilisateurDto.add(utilisateur.convertToUtilisateurDto());

    }

    System.out.println("********** listUtilisateurDto == "+listUtilisateurDto.size());

    if (listUtilisateurDto.isEmpty()) {
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    return new ResponseEntity<List<UtilisateurDto>>(listUtilisateurDto, HttpStatus.OK);
}
}

Full stacktrace:

java.lang.RuntimeException: Could not lookup value for field public java.net.URL ma.campus.services.ws.UtilisateurRestTest.deploymentURL
    at org.jboss.arquillian.test.impl.enricher.resource.ArquillianResourceTestEnricher.enrich(ArquillianResourceTestEnricher.java:68)
    at org.jboss.arquillian.test.impl.TestInstanceEnricher.enrich(TestInstanceEnricher.java:51)
    at org.jboss.arquillian.container.test.impl.ClientTestInstanceEnricher.enrich(ClientTestInstanceEnricher.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.createContext(ContainerEventController.java:128)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.createBeforeContext(ContainerEventController.java:114)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:116)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.before(EventTestRunnerAdaptor.java:98)
    at org.jboss.arquillian.junit.Arquillian$4.evaluate(Arquillian.java:216)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:384)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:231)
    at org.jboss.arquillian.junit.Arquillian$7$1.invoke(Arquillian.java:295)
    at org.jboss.arquillian.container.test.impl.execution.ClientBeforeAfterLifecycleEventExecuter.execute(ClientBeforeAfterLifecycleEventExecuter.java:88)
    at org.jboss.arquillian.container.test.impl.execution.ClientBeforeAfterLifecycleEventExecuter.on(ClientBeforeAfterLifecycleEventExecuter.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.createContext(ContainerEventController.java:128)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.createBeforeContext(ContainerEventController.java:114)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:116)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:95)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.fireCustomLifecycle(EventTestRunnerAdaptor.java:142)
    at org.jboss.arquillian.junit.Arquillian$7.evaluate(Arquillian.java:289)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:182)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:384)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:193)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:148)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.RuntimeException: All Providers for type class java.net.URL returned a null value: [org.jboss.arquillian.container.test.impl.enricher.resource.URLResourceProvider@4a194c39]
    at org.jboss.arquillian.test.impl.enricher.resource.ArquillianResourceTestEnricher.lookup(ArquillianResourceTestEnricher.java:126)
    at org.jboss.arquillian.test.impl.enricher.resource.ArquillianResourceTestEnricher.enrich(ArquillianResourceTestEnricher.java:66)
    ... 108 more

Laravel: Is it possible to directly test the json response output of a function without actually going through the URI?

From the docs, I can test some json returned from my app using the following:

$response = $this->json('POST', '/user', ['name' => 'Sally']);

$response
    ->assertStatus(201)
    ->assertJson([
        'created' => true,
    ]);

However, is it possible to bypass actually calling up the URI with $this->json(*method*, *uri*, *data*); and instead test the direct output of a controller function which returns json? For example, I want to do something like this:

// My controller:

function getPageData(){
  $data = array('array', 'of', 'data');
  return response()->json($data);
}

// My Test Class:

$controller = new Primary();
$response = $controller->getPageData();

$response->assertJson([
    'array', 'of', 'data'
]);

Is this possible?

Unespected errors when running 'ng test' or 'ng build'

My cmd displays those errors when I try to run 'ng test' and 'ng build' inside of the root directory of my Angular 5 project, but it doesn't when I run 'ng serve'.

The errors are:

ERROR in node_modules/@angular/cdk/a11y/typings/aria-describer.d.ts(15,21): error TS2304: Cannot find name 'Element'.
node_modules/@angular/cdk/a11y/typings/aria-describer.d.ts(39,27): error TS2304: Cannot find name 'Element'.
node_modules/@angular/cdk/a11y/typings/aria-describer.d.ts(41,36): error TS2304: Cannot find name 'Element'.
node_modules/@angular/cdk/a11y/typings/fake-mousedown.d.ts(15,64): error TS2304: Cannot find name 'MouseEvent'.
node_modules/@angular/cdk/a11y/typings/focus-monitor.d.ts(38,22): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/focus-monitor.d.ts(46,22): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/focus-monitor.d.ts(51,29): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/focus-monitor.d.ts(57,23): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/focus-monitor.d.ts(89,20): error TS2304: Cannot find name 'FocusEvent'.
node_modules/@angular/cdk/a11y/typings/focus-monitor.d.ts(89,41): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/focus-trap.d.ts(27,27): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/focus-trap.d.ts(27,100): error TS2304: Cannot find name 'Document'.
node_modules/@angular/cdk/a11y/typings/focus-trap.d.ts(99,21): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/interactivity-checker.d.ts(15,25): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/interactivity-checker.d.ts(24,24): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/interactivity-checker.d.ts(32,25): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/interactivity-checker.d.ts(39,26): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/list-key-manager.d.ts(56,22): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/cdk/a11y/typings/live-announcer.d.ts(9,67): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/a11y/typings/live-announcer.d.ts(30,27): error TS2304: Cannot find name 'Document'.
node_modules/@angular/cdk/bidi/typings/directionality.d.ts(20,51): error TS2304: Cannot find name 'Document'.
node_modules/@angular/cdk/layout/typings/media-matcher.d.ts(14,32): error TS2304: Cannot find name 'MediaQueryList'.
node_modules/@angular/cdk/overlay/typings/fullscreen-overlay-container.d.ts(17,29): error TS2304: Cannot find name 'Element'.
node_modules/@angular/cdk/overlay/typings/overlay-container.d.ts(12,34): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/overlay/typings/overlay-container.d.ts(21,28): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/overlay/typings/overlay-ref.d.ts(34,29): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/cdk/overlay/typings/overlay-ref.d.ts(35,53): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/overlay/typings/overlay-ref.d.ts(37,30): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/cdk/overlay/typings/overlay-ref.d.ts(57,33): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/cdk/portal/typings/dom-portal-outlet.d.ts(19,34): error TS2304: Cannot find name 'Element'.
node_modules/@angular/cdk/scrolling/typings/viewport-ruler.d.ts(32,24): error TS2304: Cannot find name 'ClientRect'.
node_modules/@angular/cdk/scrolling/typings/viewport-ruler.d.ts(42,47): error TS2304: Cannot find name 'Event'.
node_modules/@angular/cdk/stepper/typings/stepper.d.ts(96,23): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/common/http/src/client.d.ts(62,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(116,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(206,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(349,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(400,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(485,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(604,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(655,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(740,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(854,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(905,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(990,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1121,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1172,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1257,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1376,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1427,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1512,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1631,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1682,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1767,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1886,20): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(1937,30): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/client.d.ts(2018,33): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/request.d.ts(89,36): error TS2304: Cannot find name 'Blob'.
node_modules/@angular/common/http/src/request.d.ts(89,43): error TS2304: Cannot find name 'FormData'.
node_modules/@angular/common/http/src/xhr.d.ts(11,23): error TS2304: Cannot find name 'XMLHttpRequest'.
node_modules/@angular/common/src/dom_tokens.d.ts(17,47): error TS2304: Cannot find name 'Document'.
node_modules/@angular/core/src/testability/testability.d.ts(91,33): error TS2304: Cannot find name 'Node'.
node_modules/@angular/forms/src/directives/ng_form.d.ts(94,22): error TS2304: Cannot find name 'Event'.
node_modules/@angular/forms/src/directives/reactive_directives/form_group_directive.d.ts(74,22): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts(116,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts(117,25): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(157,27): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(158,26): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/button/typings/button.d.ts(75,32): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/checkbox/typings/checkbox.d.ts(161,26): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/checkbox/typings/checkbox.d.ts(164,32): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/chips/typings/chip-input.d.ts(6,12): error TS2304: Cannot find name 'HTMLInputElement'.
node_modules/@angular/material/chips/typings/chip-input.d.ts(38,30): error TS2304: Cannot find name 'HTMLInputElement'.
node_modules/@angular/material/chips/typings/chip-input.d.ts(41,22): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/chips/typings/chip-input.d.ts(46,26): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/chips/typings/chip-list.d.ts(176,21): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/chips/typings/chip.d.ts(110,25): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/chips/typings/chip.d.ts(112,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/chips/typings/chip.d.ts(132,25): error TS2304: Cannot find name 'MouseEvent'.
node_modules/@angular/material/core/typings/gestures/gesture-annotations.d.ts(25,19): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/gestures/gesture-annotations.d.ts(25,33): error TS2304: Cannot find name 'SVGElement'.
node_modules/@angular/material/core/typings/gestures/gesture-annotations.d.ts(63,19): error TS2304: Cannot find name 'EventTarget'.
node_modules/@angular/material/core/typings/gestures/gesture-config.d.ts(35,26): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/option/option.d.ts(88,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/core/typings/option/option.d.ts(97,24): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/ripple/ripple-ref.d.ts(21,14): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/ripple/ripple-ref.d.ts(25,53): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/ripple/ripple-renderer.d.ts(62,32): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/ripple/ripple.d.ts(33,14): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/ripple/ripple.d.ts(33,28): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/core/typings/style/apply-transform.d.ts(13,52): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/datepicker/typings/calendar.d.ts(78,39): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/datepicker/typings/datepicker-input.d.ts(17,20): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/datepicker/typings/datepicker-input.d.ts(24,24): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/datepicker/typings/datepicker-input.d.ts(95,23): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/datepicker/typings/datepicker-toggle.d.ts(17,18): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/datepicker/typings/datepicker.d.ts(41,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/dialog/typings/dialog-ref.d.ts(56,33): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/expansion/typings/expansion-panel-header.d.ts(33,19): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/form-field/typings/form-field-control.d.ts(51,38): error TS2304: Cannot find name 'MouseEvent'.
node_modules/@angular/material/icon/typings/icon-registry.d.ts(113,61): error TS2304: Cannot find name 'SVGElement'.
node_modules/@angular/material/icon/typings/icon-registry.d.ts(122,67): error TS2304: Cannot find name 'SVGElement'.
node_modules/@angular/material/list/typings/list.d.ts(65,24): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/list/typings/selection-list.d.ts(92,24): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/list/typings/selection-list.d.ts(128,21): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/menu/typings/menu-directive.d.ts(84,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/menu/typings/menu-item.d.ts(35,24): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/menu/typings/menu-item.d.ts(37,27): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/menu/typings/menu-trigger.d.ts(120,29): error TS2304: Cannot find name 'MouseEvent'.
node_modules/@angular/material/menu/typings/menu-trigger.d.ts(122,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/menu/typings/menu-trigger.d.ts(124,25): error TS2304: Cannot find name 'MouseEvent'.
node_modules/@angular/material/radio/typings/radio.d.ts(208,26): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/radio/typings/radio.d.ts(213,27): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/select/typings/select.d.ts(106,19): error TS2304: Cannot find name 'ClientRect'.
node_modules/@angular/material/select/typings/select.d.ts(271,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/sidenav/typings/drawer.d.ts(146,26): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts(67,27): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts(69,26): error TS2304: Cannot find name 'Event'.
node_modules/@angular/material/slider/typings/slider.d.ts(146,21): error TS2304: Cannot find name 'MouseEvent'.
node_modules/@angular/material/slider/typings/slider.d.ts(152,23): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/tabs/typings/ink-bar.d.ts(22,29): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/material/tabs/typings/tab-header.d.ts(70,27): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/material/tooltip/typings/tooltip.d.ts(89,23): error TS2304: Cannot find name 'KeyboardEvent'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(11,26): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(12,21): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(13,21): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(14,16): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(21,23): error TS2304: Cannot find name 'Element'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(23,12): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(24,21): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(25,23): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(26,42): error TS2304: Cannot find name 'MouseEvent'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(27,34): error TS2304: Cannot find name 'Event'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(28,25): error TS2304: Cannot find name 'Event'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(29,22): error TS2304: Cannot find name 'Event'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(30,22): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(31,28): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(31,35): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(32,22): error TS2304: Cannot find name 'HTMLElement'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(33,20): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(34,21): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(35,16): error TS2304: Cannot find name 'HTMLInputElement'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(36,19): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(36,26): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(37,20): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(37,27): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(38,21): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(38,28): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(39,23): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(39,30): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(40,26): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(41,26): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(42,20): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(43,21): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(43,33): error TS2304: Cannot find name 'Node'.
node_modules/@angular/platform-browser/src/browser/browser_adapter.d.ts(44,21): error TS2304: Cannot find name 'Node'.
ETC...

Dependencies of my Angular project:

"dependencies": {
    "@angular/animations": "^5.1.2",
    "@angular/cdk": "5.0.2",
    "@angular/common": "^5.1.2",
    "@angular/compiler": "^5.1.2",
    "@angular/core": "^5.1.2",
    "@angular/flex-layout": "2.0.0-beta.12",
    "@angular/forms": "^5.1.2",
    "@angular/http": "^5.1.2",
    "@angular/material": "5.0.2",
    "@angular/platform-browser": "^5.1.2",
    "@angular/platform-browser-dynamic": "^5.1.2",
    "@angular/platform-server": "^5.1.2",
    "@angular/router": "^5.1.2",
    "@covalent/core": "1.0.0-rc.1",
    "@covalent/dynamic-forms": "1.0.0-rc.1",
    "@covalent/highlight": "1.0.0-rc.1",
    "@covalent/http": "1.0.0-rc.1",
    "@covalent/markdown": "1.0.0-rc.1",
    "@ng-bootstrap/ng-bootstrap": "^1.1.2",
    "@swimlane/ngx-charts": "^7.0.1",
    "codemirror": "^5.22.2",
    "core-js": "^2.4.1",
    "d3": "^4.12.2",
    "ecstatic": "^3.1.1",
    "hammerjs": "^2.0.8",
    "highlight.js": "9.12.0",
    "line-diff": "^2.0.0",
    "ng2-breadcrumbs": "^0.1.281",
    "ng2-codemirror": "1.1.3",
    "rich-text-diff": "^0.2.3",
    "rxjs": "^5.2.0",
    "showdown": "1.8.6",
    "ssri": "^5.3.0",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular/cli": "^1.6.3",
    "@angular/compiler-cli": "^5.1.2",
    "@angular/language-service": "^5.1.2",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "^8.5.8",
    "codelyzer": "~4.0.2",
    "coveralls": "^3.0.0",
    "http-server": "0.10.x",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.3.3",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.2.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.8.0",
    "typescript": "^2.5.3"
  }

The fact is that when I run 'ng serve', I don't view any error, but when I try to run the tests I receive those errors.

Without solving this error I can't run and test my tests so what am I doing wrong?

Using RSpec to test for the queue is divided into two streams

Could you help me to test the queue. I'm new comer in rails and rspec.

it "the queue should be divided into two streams" do
     Queue.all
     expect(Queue.all.split(2)).to eq(2)
   end

but it doesn't work

Is there any tool to test spark program's parallel efficiency?

I want to know a spark program's parallel efficiency. But I have no enough machine to test it. So is there any tool or method can obtain parallel efficiency without spark cluster.

Drupal 8 Functional Testing Node Update Fails

I'm trying to write a function test for some behaviour that will occur in hook_node_presave()

In the test I create two nodes and test the association between them, which works fine.

class TestNewsItemsAreReassociatedTest extends BrowserTestBase {

  /**
   * The installation profile to use with this test.
   *
   * @var string
   */
  protected $profile = 'standard';

  /**
   * Enabled modules
   */
  public static $modules = [
    'custom_services_industries',
  ];

  /**
   * {@inheritdoc}
   */
  function setUp() {
    parent::setUp();
  }

  /**
   * Test associations change.
   */
  public function testAssociationsChange() {

    // Create nodes to test.
    $service = $this->drupalCreateNode(['type' => 'service_and_industry']);
    $news = $this->drupalCreateNode(['type' => 'news', 'field_related_services' => $service->id()]);

    // Check the service is related to the news item.
    $relatedService = $news->get('field_related_services')->getValue();
    $this->assertEquals([0 => ['target_id' => $service->id()]], $relatedService);

    // Check the news is not related to an industry.
    $relatedIndustry = $news->get('field_related_industries')->getValue();
    $this->assertEmpty($relatedIndustry);

  }

}

Then I need to update a field value in one node, which I attempt to to do like this

// Change the service type.
$service = node_load($service->id());
$service->set('field_service_type', ['industry']);
$service->save();

But this fails with the error

Drupal\Core\Entity\EntityStorageException : SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘test_site.node__field_related_services' doesn't exist:

All the tables in the database are prefixed with test73350856 but surely Drupal would take care of database prefixes.

How do I update a field’s value and then save the node in a functional test?

Mockito expcetion

I am new with testing. I have tried this one but got an exception.

@Mock
private Context context;    
when(service.getResult(any(), context)).thenReturn(new ArrayList<>());

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:

vendredi 27 avril 2018

How to ignore Generated files from Go test coverage

I have a generated file in my package with DO NOT EDIT on top. I am running tests for my package with go test -coverprofile=cover.out <package>. This creates coverage profile and shows total coverage percentage. But it also includes generated files while calculating the coverage. Is there a way to ignore generated files in coverage calculation?

How to implement a server for a python scripts testing system (with stdio)?

Could you advice how to implement server for scripts testing such as like on coursera.

There is input, where pupil attach their script. And next steps is quite foggy for me as I see them:

  1. server get script
  2. server checks extension of script
  3. server runs bash script with testing data(std input), waits for result >> creates output file
  4. output file is compared with solution
  5. server sends response

Is it right? Are there any other solutions?

http-only site to test REST requests?

After the latest move by httpbin to HTTPS, apparently all sites that accepted test REST requests have disappeared. I've checked all mentioned in this post, and either they do not allow all kind of requests, or have also moved to HTTPS. In perl 6 modules such as this one, LWP::Simple, we need a HTTP-only site due to problems with certain operating systems. So is there any site left or will we have to roll out our own server?

Best practice of using unittest kind asserts (like assertNotIn) in standalone pytest tests?

In standalone pytest test cases I would like to use assertions like unittest.TestCase.assertNotIn (and unittests other asserts) without any dependency on the uniittest module. Is best practice to use libraries like python-assert?

Testing razor pages app

I am writing a Razor Pages app for a University project, which I am required to test. I couldn't find many sources and examples online on testing Razor Pages and I'm trying to follow the examples on this link : https://docs.microsoft.com/en-us/aspnet/core/testing/razor-pages-testing?view=aspnetcore-2.1

My first problem is unit testing:
This is the test method I wrote, it's supposed to check that a value that is filled in the OnGet method on my model is receiving the correct value:

[Fact]
    public void OnGet_ViewStores()
    {
        // Arrange
        var httpContext = new DefaultHttpContext();
        var modelState = new ModelStateDictionary();
        var actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
        var modelMetadataProvider = new EmptyModelMetadataProvider();
        var viewData = new ViewDataDictionary(modelMetadataProvider, modelState);
        var pageContext = new PageContext(actionContext)
        {
            ViewData = viewData
        };
        var storesModel = new StoresModel()
        {
            PageContext = pageContext,
            Url = new UrlHelper(actionContext)
        };

        #region snippet2
        // Act
        storesModel.OnGet();
        #endregion

        #region snippet3
        // Assert
        var actualStores = wsep1.Services.ViewAllStores(1);
        Assert.Equal(storesModel.StoreDetails, actualStores);
        #endregion
    }

And this is the model which is being checked:

public class StoresModel : PageModel
{
    public List<string> StoreDetails { get; set; }
    public string Message { get; set; }
    public int clientId;

    public void OnGet()
    {
        clientId = (int)HttpContext.Session.GetInt32("clientId");
        Message = "Your clientId id is " + clientId;
        StoreDetails = wsep1.Services.ViewAllStores(clientId);
    }
}

The problem is that the test throws an exception because I am using an HttpContext.Session which is not configures properly in the test. In my real project it is configured beforehand in Startup.cs in this method:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddWebSocketManager();
        services.AddMvc();
        services.AddDistributedMemoryCache();
        services.AddTransient<ShoppingHandler>();
        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(1000);
            options.Cookie.HttpOnly = true;
        });
    }

But I can't seem to find a way to configure this in my test.

My second problem is with integration testing:
I am trying to run a very basic test with the Test Server, this is my test class:

   public class IndexPageTest : IClassFixture<TestFixture<Client.Startup>>
{
    private readonly HttpClient _client;

    public IndexPageTest(TestFixture<Client.Startup> fixture)
    {
        _client = fixture.Client;
    }

    #region snippet1
    [Fact]
    public async Task Request_ReturnsSuccess()
    {
        // Act
        var response = await _client.GetAsync("/");

        // Assert
        response.EnsureSuccessStatusCode();
    }
    #endregion
}  

I hardly changed the TextFixture class that was included in the demo project in the link I gave at the beginning of the post, all I did was add my services to the configuration method (as I said before, I'm using a Session object and also WebSocketManager in my app).
_client.GetAsync("/") returns a status of "500 - internal server error" and I have no idea why and how to configure these tests to work.
Any ideas would be appreciated, Thanks.