Katalon: How to use the result of one test case in an another test case? - katalon-studio

I have 2 different test cases which have different URL's.
Common thing between two URL's is the unique ID. I have captured the URL of one test case and split the URL of that test case and stored the ID in a variable. I made that variable a global variable and tried to use it in 2nd test case.
Now, I want to use that ID obtained from 1st test case in 2nd test case.
I got the error below:
**Test Case FAILED because (of) org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'ba0eed2c-cba8-11e8-86a5-02e9072e0d95' with class 'java.lang.String' to class 'internal.GlobalVariable'**
**Code for Test Case A is as follows:**
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.checkpoint.CheckpointFactory as CheckpointFactory
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as MobileBuiltInKeywords
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testcase.TestCaseFactory as TestCaseFactory
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testdata.TestDataFactory as TestDataFactory
import com.kms.katalon.core.testobject.ObjectRepository as ObjectRepository
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WSBuiltInKeywords
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUiBuiltInKeywords
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable as GlobalVariable
import org.openqa.selenium.Keys as Keys
WebUI.click(findTestObject('PO_ID_Details_Passport/label_Select Document Type'))
WebUI.click(findTestObject('PO_ID_Details_Passport/li_Passport'))
WebUI.setText(findTestObject('PO_ID_Details_Passport/input_PO_PASSPORT_NUMBER'), 'Test123456')
WebUI.setText(findTestObject('PO_ID_Details_Passport/input'), '25')
WebUI.setText(findTestObject('PO_ID_Details_Passport/input_1'), '05')
WebUI.setText(findTestObject('PO_ID_Details_Passport/input_2'), '2025')
// Capture the current URL and split the URL to get the unique ID.
String url = WebUI.getUrl()
String getQueryString = url.split("\\?")[1]
String[] getFields = getQueryString.split("&")
Map<String, String> fieldValueMap = new HashMap<String, String>()
for(String field : getFields) {
fieldValueMap.put(field.split("=")[0], field.split("=")[1])
}
println fieldValueMap.get("JID")
GlobalVariable JourneyID=fieldValueMap.get("JID")
//return JourneyID
Thread.sleep(5000)
WebUI.click(findTestObject('PO_ID_Details_Passport/Upload_File'))
Thread.sleep(3000)
//Sample path. Change it to your saved location of autoIT script
Runtime.getRuntime().exec('ABC')
Thread.sleep(5000)
WebUI.click(findTestObject('PO_ID_Details_Passport/i'))
]
How can I use the value of JourneyID in different test case?

you can use A global variable to store value as shown below.
GlobalVariable.JourneyID=fieldValueMap.get("JID")
But before using this variable, create a Global Variable named 'JourneyID' and pass some static value to it.
Now you can use it in other test cases.
Hope this will help you.

Related

How to create a serializer for decimal in flutter

I want to create a Company model from json API.
This is the code for it.
company.dart
import 'dart:convert' as json;
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:decimal/decimal.dart';
import 'serializers.dart';
part 'company.g.dart';
abstract class Company implements Built<Company, CompanyBuilder> {
static Serializer<Company> get serializer => _$companySerializer;
int get code;
#nullable
String get name;
#nullable
Decimal get price;
Company._();
factory Company([updates(CompanyBuilder b)]) = _$Company;
}
When I use int get price instead of Decimal get price, the code works fine. (Of course I also need to change server side code.)
This code fails with this error.
Deserializing '[code, 1000, name, company_name, price: 100.0, ...' to 'Company' failed due to: Bad state: No serializer for 'Decimal'.
The serializer is created by the commend flutter packages pub run build_runner build.
Probably I need to tell the serializer how to treat Decimal, but I don't know how.
This is serializers.dart.
library serializers;
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
import 'company.dart';
part 'serializers.g.dart';
#SerializersFor(const [Company])
final Serializers serializers = _$serializers;
Serializers standardSerializers =
(serializers.toBuilder()..addPlugin(new StandardJsonPlugin())).build();
How should I change the code?

Why Use PathVariable instead of PathParam?

Before marking this as duplicate, just wanted you guys to know I have checked out the question posted here:
What is the difference between #PathParam and #PathVariable
Thing is, if the usage of PathParam and PathVariable are same (only that one is from the JAX-RS API and one is provided by Spring), why is it that using one gives me null and the other gives me the proper value?
I am using Postman to invoke the service as:
http://localhost:8080/topic/2
(I'm very new to SpringBoot)
Using PathParam :
import javax.websocket.server.PathParam;
import org.apache.tomcat.util.json.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TopicController {
#Autowired
TopicService topicService;
#RequestMapping(method=RequestMethod.GET,path="/topic/{id}")
public Topic getById(#PathParam("id") long id) throws ParseException {
return topicService.getTopicById(id); //-- here id comes as null (when id is declared as a wrapper type - Long, else it throws an error)
}
}
Using PathVariable:
#RestController
public class TopicController {
#Autowired
TopicService topicService;
#RequestMapping(method=RequestMethod.GET,path="/topic/{id}")
public Topic getById(#PathVariable("id") long id) throws ParseException {
return topicService.getTopicById(id); //-- here id comes as 2
}
}
I think the pathparam in your project is under javax.ws... This one is not what they talked about. It is used in websocket, which means it is not a http annotaiton. JBoss implement pathparam needs additional jars.

AEM - How to return page information in JSON format

I need to display the title and name of all child and grand child pages from given path in JSON format. Please provide the implementation.
First You have to try something yourself, then you call for help, not the complete solution!anyway there are couple of solution down there.
According to Adobe here you can implement page information in JSON format:
package com.adobe.example;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.Reference;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageInfoProvider;
#Component(metatype = false)
#Properties({
#Property(name="service.description", value="Returns the public URL of a resource.")
})
#Service
public class PageUrlInfoProvider implements PageInfoProvider {
#Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY)
private com.day.cq.commons.Externalizer externalizer;
private String fetchExternalUrl(ResourceResolver rr, String path) {
return externalizer.publishLink(rr, path);
}
public void updatePageInfo(SlingHttpServletRequest request, JSONObject info, Resource resource)
throws JSONException {
Page page = resource.adaptTo(Page.class);
JSONObject urlinfo = new JSONObject();
urlinfo.put("publishURL", fetchExternalUrl(null,page.getPath()));
info.put("URLs",urlinfo);
}
}
Or you may try this Page for solution
Please refer to below link which may be useful:
http://www.nateyolles.com/blog/2015/12/converting-aem-sling-resources-to-json.
Apart from the above solution you also use recursive level to get the data in the JSON format for example /content/we-retail/language-masters/en.{placeholder}.json
replace the placeholder with the level of nodes you want to print and return back the JSON wherever needed.
To know more about the rendering data in different formats,
Refer: https://sling.apache.org/documentation/bundles/rendering-content-default-get-servlets.html

Using restframework mongoengine how to create a queires?

models.py
from mongoengine import Document, fields
class Tool(Document):
Fruit = fields.StringField(required=True)
District = fields.StringField(required=True)
Area = fields.StringField(required=True)
Farmer = fields.StringField(required=True)
Serializers.py file
from rest_framework import serializers
from rest_framework_mongoengine.serializers import DocumentSerializer
from models import Tool
class ToolSerializer(DocumentSerializer):
class Meta:
model = Tool
views.py file
from django.template.response import TemplateResponse
from rest_framework_mongoengine.viewsets import ModelViewSet as MongoModelViewSet
from app.serializers import *
def index_view(request):
context = {}
return TemplateResponse(request, 'index.html', context)
class ToolViewSet(MongoModelViewSet):
lookup_field = 'Fruit'
serializer_class = ToolSerializer
def get_queryset(self):
return Tool.objects.all()
So,I want to create queries like http://127.0.0.1:8000/api/tool/?Fruit=Banana gives me all data for fruit banana only. Also, http://127.0.0.1:8000/api/tool/?District=Pune gives me data for Pune district only .
Unfortunately, I haven't tried this solution myself yet, but AFAIK, in pure DRF with SQL database you'd use Django-Filters package for this.
There's an analogue of it for DRF-ME, called drf-mongo-filters, written by Maxim Vasiliev, co-author of DRF-ME. It contains a decent set of tests, you could use for inspiration.
Basically, you say something like:
from rest_framework.test import APIRequestFactory
from rest_framework.generics import ListAPIView
from mongoengine import Document, fields
from drf_mongo_filters.filtersets import filters, Filterset, ModelFilterset
from drf_mongo_filters.backend import MongoFilterBackend
class TestFilter(Filterset):
foo = filters.CharFilter()
class TestView(ListAPIView):
filter_backends = (MongoFilterBackend,)
filter_class = TestFilter
serializer_class = mock.Mock()
queryset = mock.Mock()
TestView.as_view()(APIRequestFactory().get("/?foo=Foo"))
TestView.queryset.filter.assert_called_once_with(foo="Foo")
Haven't tried doing the same with ViewSets, but as they inherit from GenericView, I guess, they should respect filter_class and filter_backends parameters, too.

Scala + Play Framework: Basic Form

I'm trying to create a basic form with username/password and save the results in a database, just to get familiar with it.
Step one and I'm a little stuck: I can't get the app to render the form in my browser. Once I can do that, I figure I'll move on to getting my database set up. But every time I try to run my app, I get this error:
Cannot write an instance of play.api.Form[models.User] to http response. Try to define a Writable[play.api.Form[models.User]]
I spent my entire day searching for the solution to this problem. Here are my files:
Application.scala (controller class):
package controllers
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models._
class Application extends Controller {
val userForm = Form(
mapping(
"username" -> nonEmptyText,
"password" -> nonEmptyText
)(User.apply)(User.unapply)
)
def index = Action {
Ok(userForm)
}
}
users.scala.html (view):
#(user: Form[models.User])(implicit message: Messages)
#import helper._
#main(Messages("Feedback")) {
<h2>#Messages("Leave Feedback")</h2>
<form>
#inputText("username")
#inputText("password")
<input type="submit" value="#Messages("send")">
</form>
}
Routes file:
# Home page
GET / controllers.Application.index
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
Cannot write an instance of play.api.Form[models.User] to http response. Try to define a Writable[play.api.Form[models.User]]
The complied error has given the hint that the data sent should be a Form which is just the userForm as for your question, and the Form should be filled with models.User
As for your question, you just need to do the following things
Firstly, define a form Models.User data you want to send in your controller.
val userData = Models.User("name", "password")//Models.User is a case class
if you want to send a form data to the views, you must define a variable data with the type of Models.User firstly. In your code, you have created a form data userForm mapping to the models.user. The next thing you should do is to create a value userData with type of models.user, which can be filled into the userForm using userForm.fill(userData). Then the userForm filled full of Models.User data can be sent to the views.
Then, send it to the views using the following way
Ok(views.html.users(userForm.fill(userData)))
So, all the answer to your question will like this
package controllers
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models._
class Application extends Controller {
val userForm = Form(
mapping(
"username" -> nonEmptyText,
"password" -> nonEmptyText
)(User.apply)(User.unapply)
)
def index = Action {
val userData = Models.User("yourName", "yourPassword")// the Models.User value is a case class
Ok(views.html.users(userForm.fill(userData)))
}
}
Have a good luck