Restsharp107.3.0 Sequential mock execution is failing when trying InSequence operation in unittest - restsharp

I am converting Restsharp .netcore3.1 version to .Net6.0 with latest version of Restsharp107.3.0.
Existing test case was failing due to the interfaces were changed to classes also RestRequestAsyncHandle is not supported in latest version.
Please show some light on this if you faced any issue like this.
Expected result: Need to mock test to validate HttpStatusCode.RequestTimeout and HttpStatusCode.OK in sequence order.
// Arrange
var restClient = new Mock<RestClient>();
// Create the MockSequence to validate the call order
var sequence = new MockSequence();
restClient
.InSequence(sequence).Setup(x => x.ExecuteAsync(
It.IsAny<RestRequest>(),
It.IsAny<Action<RestResponse, RestRequestAsyncHandle>>()))
.Callback<RestRequest, Action<RestResponse, RestRequestAsyncHandle>>
((request, callback) =>
{
callback(new RestResponse { StatusCode =
HttpStatusCode.RequestTimeout }, null);
});
restClient
.InSequence(sequence).Setup(x => x.ExecuteAsync(
It.IsAny<RestRequest>(),
It.IsAny<Action<RestResponse, RestRequestAsyncHandle>>()))
.Callback<RestRequest, Action<RestResponse, RestRequestAsyncHandle>>
((request, callback) => { callback(new RestResponse {
StatusCode = HttpStatusCode.OK }, null);});

Related

Extracting Identity from lambda authorizer response

I made a custom lambda authorizer that validates the JWT and returns Allow policy.
var context = new APIGatewayCustomAuthorizerContextOutput();
var tokenUse = ExtractClaims(claims, "token_use");
context["tokenType"] = tokenUse;
var response = new APIGatewayCustomAuthorizerResponse
{
PrincipalID = "asd",
PolicyDocument = new APIGatewayCustomAuthorizerPolicy
{
Version = "2012-10-17",
Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>()
{
new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
{
Action = new HashSet<string>() {"execute-api:Invoke"},
Effect = "Allow",
Resource = new HashSet<string>() {"***"} // resource arn here
}
},
},
Context = context
};
return response;
Now I need to use this Identity on my resource server.
The problem is that the claims I put in the authorizer context appears under authorizer directly
"authorizer": {
"cognito:groups": "Admin", ...
}
but my Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction expects those under authorizer.claims.
like such:
"authorizer": {
"claims": {
"cognito:groups": "Admin", ...
}
}
And I know that, because it was working when I was using the built in Cognito User Pool authorizer, which was making the input like that.
I managed to find that Lambda Authorizer is not allowed to add nested objects to the context (and tested that it throws authorizer error if I do.)
I also found that when APIGatewayProxyFunction is extracting the Identity, it looks at Authorizer.Claims.
So I need to either extract them on my resource server bypassing the Claims property somehow, or add a nested object to the authorizer response, which is not allowed.
What do?
So I solved this by overriding the PostCreateContext method on my LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.
protected override void PostCreateContext(
HostingApplication.Context context,
APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext)
{
// handling output from cognito user pool authorizer
if (apiGatewayRequest?.RequestContext?.Authorizer?.Claims != null)
{
var identity = new ClaimsIdentity(apiGatewayRequest.RequestContext.Authorizer.Claims.Select(
entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity");
context.HttpContext.User = new ClaimsPrincipal(identity);
return;
}
// handling output from lambda authorizer
if (apiGatewayRequest?.RequestContext?.Authorizer != null)
{
var identity = new ClaimsIdentity(apiGatewayRequest.RequestContext.Authorizer.Select(
entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity");
context.HttpContext.User = new ClaimsPrincipal(identity);
}
}
Edit: also submitted a pull reqeust to the aws-lambda-dotnet library fixing this.
Edit 2: My pull request has been merged for some time and this is not an issue anymore if using an up to date Amazon.Lambda.AspNetCoreServer (not sure which version first had it, but 3.1.0 definitely has it)

error handling in angular 5, catch errors from backend api in frontend

I need advise for handling errors in front-end of web application.
When I call a service to get the community according to community in web app, I want it to catch an error. For example for catching errors like 404.
There is a service for getting community according to id provided.
getCommunity(id: number) {
return this.http.get(`${this.api}/communities/` + id + ``);
}
that is called in events.ts file
setCommunityBaseUrl() {
this.listingService.getCommunity(environment.communityId).subscribe((data: any) => {
this.communityUrl = data.url + `/` + data.domain;
});
}
The id is provided in environment. Let's say there are 20 communities in total. When I provide id = 1 the events according to community = 1 appears.
export const environment = {
production: ..,
version: 'v2',
apiUrl: '...',
organization: '...',
websiteTitle: '...',
communityId: 1,
googleMapsApiKey: '...'
};
The problem is that when I provide id = null all community events are occurring | all events list in the backend is occurring.
Please, help ^^
When you subscribe you subscribe with an Observer pattern. So the first function you pass in
.subscribe(() => {} );
fires when the Observable calls .next(...)
and after that you can provide another function which will fire whenever the Observable calls .error(...)
so
.subscribe(() => {}, (error) => { handleTheError(error); } );
The this.http.get(...); returns an Observable which will fire the .error(...) on http error
We also know that this.http.get(...) completes or "errors" and it's not an endless one (a one that never completes). So you can make it a promise and manipulate on it promise like.
async getMeSomething(...) {
try {
this.mydata = await this.http.get(...).toPromise();
}
catch(error) {
handleTheError(error)
}
}
But what I really recommend is to use Swagger for your backend and then generate the API Client class with NSwagStudio so you don't have to write the client manually or adjust it or deal with error catching. I use it all the time and it saves us an enormous amount of time
Because you are using ".subscribe" you can create your own error handler and catch the errors like this, directly on the method.
This is an example on how you can use this:
constructor(
private _suiteAPIService: SuitesAPIService,
private _testcaseService: TestcaseService,
public _tfsApiService: TfsApiService,
private _notificationService: NotificationService) { }
errorHandler(error: HttpErrorResponse) {
return observableThrowError(error.message || "Server Error")
}
public something = "something";
GetTestcasesFromSuiteSubscriber(Project, BuildNumber, SuiteId) {
this._suiteAPIService.GetTestResults(Project, BuildNumber, SuiteId).subscribe(
data => {
console.log(data);
this._testcaseService.ListOfTestcases = data;
//Notofication service to get data.
this._notificationService.TestcasesLoaded();
},
error => {
//Here we write som error
return this.something;
}
);
}

CucumberJS tests passing even though it's not possible

I'm trying to convert some old ruby tests (which used cucumber, phantomjs and capybara) into JavaScript (using cucumber, phantomjs and selenium) as my project is 100% node based and I want to remove the Ruby dependency.
When I run the tests, they all pass. The problem is, I've not created the conditions for the test to pass yet so a pass is impossible. I'm not sure where I'm going wrong.
Here is my world.js file:
var {defineSupportCode} = require('cucumber');
var seleniumWebdriver = require('selenium-webdriver'),
By = seleniumWebdriver.By,
until = seleniumWebdriver.until;
function CustomWorld() {
this.driver = new seleniumWebdriver.Builder()
.withCapabilities(seleniumWebdriver.Capabilities.phantomjs())
.build()
// Returns a promise that resolves to the element
this.waitForElement = function(locator) {
var condition = seleniumWebdriver.until.elementLocated(locator);
return this.driver.wait(condition)
}
}
defineSupportCode(function({setWorldConstructor}) {
setWorldConstructor(CustomWorld)
});
And here is my step definitions file:
require('dotenv').config();
var chalk = require('chalk');
var {defineSupportCode} = require('cucumber');
var seleniumWebdriver = require('selenium-webdriver'),
By = seleniumWebdriver.By,
until = seleniumWebdriver.until;
defineSupportCode(function({ Given, When, Then }) {
Given(/^I show my environment$/, function (next) {
console.log(chalk.green("Running against:" + process.env.TARGET_URI))
next()
})
When(/^I visit "(.*?)"$/, function (url) {
return this.driver.get(url);
})
Then(/^I should be on "([^"]*)"$/, function(page_name) {
this.driver.get(process.env.TARGET_URI+'/'+page_name)
.then(function() {
return this.driver.getCurrentUrl();
})
})
Then(/^I should see "([^"]*)"$/, function (text) {
var xpath = "//*[contains(text(),'" + text + "')]";
var condition = seleniumWebdriver.until.elementLocated({xpath: xpath});
return this.driver.wait(condition, 5000);
});
})
The only possible tests that could be passing there are: When(/^I visit "(.*?)"$/... and Given(/^I show my environment$/...
For reference, here is my .feature file too:
Feature: Test the global header works as expected
Scenario: Header components should exist
Given I visit "/hello"
Then I expect to see a ".c-logo-bar" element
And I expect to see a ".c-search-bar" element
And I expect to see a ".c-main-nav-bar" element
Any ideas where I'm going wrong?

Angular2 - Multiple dependent sequential http api calls

I am building an Angular2 app and one of the components needs to make multiple API calls which are dependent on the previous ones.
I currently have a service which makes an API call to get a list of TV shows. For each show, I then need to call a different API multiple times to step through the structure to determine if the show exists on a Plex server.
The API documentation is here
For each show, I need to make the following calls and get the correct data to determine if it exists: (Assume we have variables <TVShow>, <Season>, <Episode>)
http://baseURL/library/sections/?X-Plex-Token=xyz will tell me:
title="TV Shows" key="2"
http://baseURL/library/sections/2/all?X-Plex-Token=xyz&title=<TVShow> will tell me: key="/library/metadata/2622/children"
http://baseURL/library/metadata/2622/children?X-Plex-Token=xyz will tell me: index="<Season>" key="/library/metadata/14365/children"
http://baseURL/library/metadata/14365/children?X-Plex-Token=xyz will tell me: index="<Episode>" which implies that the episode I have exists.
The responses are in json, I have removed a lot of the excess text. At each stage I need to check that the right fields exist (<TVShow>, <Season>, <Episode>) so that they can be used for the next call. If not, I need to return that the show does not exist. If it does, I will probably want to return an id for the show.
I have looked at lots of examples including promise, async & flatmap, but am not sure how to solve this based on the other examples I have seen.
How to chain Http calls in Angular2
Angular 2.0 And Http
Angular 2 - What to do when an Http request depends on result of another Http request
Angular 2 chained Http Get Requests with Iterable Array
nodejs async: multiple dependant HTTP API calls
How to gather the result of Web APIs on nodeJS with 'request' and 'async'
Here is what I have for getting the list of shows. (shows.service.ts)
export class ShowsHttpService {
getShows(): Observable<Show[]> {
let shows$ = this._http
.get(this._showHistoryUrl)
.map(mapShows)
.catch(this.handleError);
return shows$;
}
}
function mapShows(response:Response): Show[] {
return response.json().data.map(toShow);
}
function toShow(r:any): Show {
let show = <Show>({
episode: r.episode,
show_name: r.show_name,
season: r.season,
available : false, // I need to fill in this variable if the show is available when querying the Plex API mentioned above.
});
// My best guess is here would be the right spot to call the Plex API as we are dealing with a single show at a time at this point, but I cannot see how.
return show;
}
Here is the relevant code from the component (shows.component.ts)
public getShows():any {
this._ShowsHttpService
.getShows()
.subscribe(w => this.shows = w);
console.log(this.shows);
}
Bonus points
Here are the obvious next questions that are interesting, but not necessary:
The first API query will be much faster than waiting for all of the other queries to take place (4 queries * ~10 shows). Can the initial list be returned and then updated with the available status when it is ready.
The first Plex call to get the key="2" only needs to be performed once. It could be hard coded, but instead, can it be performmed once and remembered?
Is there a way to reduce the number of API calls? I can see that I could remove the show filter, and search through the results on the client, but this doesn't seam ideal either.
The 4 calls for each show must be done sequentially, but each show can be queried in parallel for speed. Is this achievable?
Any thoughts would be much appreciated!
Not sure if I totally understand your question, but here is what I do:
I make the first http call, then when the subscribe fires, it calls completeLogin. I could then fire another http call with its own complete function and repeat the chain.
Here is the component code. The user has filled in the login information and pressed login:
onSubmit() {
console.log(' in on submit');
this.localUser.email = this.loginForm.controls["email"].value;
this.localUser.password = this.loginForm.controls["password"].value;
this.loginMessage = "";
this.checkUserValidation();
}
checkUserValidation() {
this.loginService.getLoggedIn()
.subscribe(loggedIn => {
console.log("in logged in user validation")
if(loggedIn.error != null || loggedIn.error != undefined || loggedIn.error != "") {
this.loginMessage = loggedIn.error;
}
});
this.loginService.validateUser(this.localUser);
}
This calls the loginservice ValidateUser method
validateUser(localUser: LocalUser) {
this.errorMessage = "";
this.email.email = localUser.email;
var parm = "validate~~~" + localUser.email + "/"
var creds = JSON.stringify(this.email);
var headers = new Headers();
headers.append("content-type", this.constants.jsonContentType);
console.log("making call to validate");
this.http.post(this.constants.taskLocalUrl + parm, { headers: headers })
.map((response: Response) => {
console.log("json = " + response.json());
var res = response.json();
var result = <AdminResponseObject>response.json();
console.log(" result: " + result);
return result;
})
.subscribe(
aro => {
this.aro = aro
},
error => {
console.log("in error");
var errorObject = JSON.parse(error._body);
this.errorMessage = errorObject.error_description;
console.log(this.errorMessage);
},
() => this.completeValidateUser(localUser));
console.log("done with post");
}
completeValidateUser(localUser: LocalUser) {
if (this.aro != undefined) {
if (this.aro.errorMessage != null && this.aro.errorMessage != "") {
console.log("aro err " + this.aro.errorMessage);
this.setLoggedIn({ email: localUser.email, password: localUser.password, error: this.aro.errorMessage });
} else {
console.log("log in user");
this.loginUser(localUser);
}
} else {
this.router.navigate(['/verify']);
}
}
In my login service I make a call to the authorization service which returns an observable of token.
loginUser(localUser: LocalUser) {
this.auth.loginUser(localUser)
.subscribe(
token => {
console.log('token = ' + token)
this.token = token
},
error => {
var errorObject = JSON.parse(error._body);
this.errorMessage = errorObject.error_description;
console.log(this.errorMessage);
this.setLoggedIn({ email: "", password: "", error: this.errorMessage });
},
() => this.completeLogin(localUser));
}
In the authorization service:
loginUser(localUser: LocalUser): Observable<Token> {
var email = localUser.email;
var password = localUser.password;
var headers = new Headers();
headers.append("content-type", this.constants.formEncodedContentType);
var creds:string = this.constants.grantString + email + this.constants.passwordString + password;
return this.http.post(this.constants.tokenLocalUrl, creds, { headers: headers })
.map(res => res.json())
}
The point here in this code, is to first call the validateUser method of the login service, upon response, based on the return information, if its valid, I call the loginUser method on the login service. This chain could continue as long as you need it to. You can set class level variables to hold the information that you need in each method of the chain to make decisions on what to do next.
Notice also that you can subscribe to the return in the service and process it there, it doesn't have to return to the component.
Okay, Here goes:
public getShows():any {
this._ShowsHttpService
.getShows()
.subscribe(
w => this.shows = w,
error => this.errorMessage = error,
() => this.completeGetShows());
}
completeGetShow() {
//any logic here to deal with previous get;
this.http.get#2()
.subscribe(
w => this.??? = w),
error => this.error = error,
() => this.completeGet#2);
}
completeGet#2() {
//any logic here to deal with previous get;
this.http.get#3()
.subscribe(
w => this.??? = w),
error => this.error = error,
() => this.completeGet#3);
}
completeGet#3() {
//any logic here to deal with previous get;
//another http: call like above to infinity....
}

TestCases collections is not retrieved correctly through SDK but only with Web Service api

SDK retrieval of TestCases collection from the TestSet object is not working correctly IMO as TestCase collection is not a full array of objects and TestCases collection has very scarce information.
Web service API returns them correctly and so far only 2.0p5 returns them correctly and neither of 2.0rc rc2 and rc3 returns them as expected
Am I doing something wrong?
I just need to get TestCases collection with all fully qualified objects for each test case when I retrieve a TestSet object.
AppSDK rc2 works with v2.0 of WS API. v2.0 removed the ability to return child collections in the same response for performance reasons. Per WS API documentation fetching a collection will return an object with the count and the url from which to get the collection data. To get full objects a separate request is needed. In app example in this github repo when a testset is selected from a combobox, and testset loaded, TestCases collection is hydreated:
_onDataLoaded: function(store, records){
if ((records.length === 0) && (this._grid)) {
this._grid.destroy();
}
var that = this;
var promises = [];
_.each(records, function(tcr) {
promises.push(that._getTestCase(tcr, that));
});
Deft.Promise.all(promises).then({
success: function(results) {
that._testcaseresults = results;
that._createGrid(records);
}
});
},
_getTestCase: function(tcr, scope) {
var deferred = Ext.create('Deft.Deferred');
var that = scope;
var testcaseOid = tcr.get('TestCase').ObjectID;
Rally.data.ModelFactory.getModel({
type: 'Test Case',
scope: this,
success: function(model, operation) {
fetch: ['FormattedID','Name','Method'],
model.load(testcaseOid, {
scope: this,
success: function(record, operation) {
var testName = record.get('Name');
var testFid = record.get('FormattedID');
var testMethod = record.get('Method');
var tcrRef = tcr.get('_ref');
var tcrOid = tcr.get('ObjectID');
var tcrVerdict = tcr.get('Verdict');
var tcrBuild = tcr.get('Build');
result = {
"_ref" : tcrRef,
"ObjectID" : tcrOid,
"Verdict" : tcrVerdict,
"Build" : tcrBuild,
"TestCaseName" : testName,
"TestCase" : testFid,
"Method" : testMethod
};
deferred.resolve(result);
}
});
}
});
return deferred;
}