Unable to capture screenshot using ExtentReport version 4-- Selenium-Java - extentreports

Unable to capture a screenshot using extent report 4(Selenium-Java)
Error msg is :-
FAILED CONFIGURATION: #AfterMethod tearDown([TestResult name=expediaTitleCheck status=FAILURE method=Expedia_TC.expediaTitleCheck()[pri:0, instance:com.extent.testcases.Expedia_TC#72b6cbcc] output={null}])
Code is as follows:-
public class Expedia_TC {
WebDriver driver;
Expedia exp;
ExtentHtmlReporter htmlReport;
ExtentReports extent;
ExtentTest test;
#BeforeTest
public void startBrowser() {
htmlReport = new ExtentHtmlReporter(System.getProperty("user.dir")+"/Reports/ExpediaReport.html");
htmlReport.config().setEncoding("utf-8");
htmlReport.config().setDocumentTitle("Expedia Automation Report");
htmlReport.config().setReportName("Functional Report");
htmlReport.config().setTimeStampFormat("EEEE,DD-MM-YYYY,hh:mm:ss");
htmlReport.config().setTheme(Theme.DARK);
extent = new ExtentReports();
extent.attachReporter(htmlReport);
extent.setSystemInfo("OS","Windows10");
extent.setSystemInfo("Environment","Production");
extent.setSystemInfo("Tester","Jayashree");
WebDriverManager.firefoxdriver().setup();
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, "true");
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"/dev/null");
driver = new FirefoxDriver();
exp = new Expedia(driver);
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
}
#Test
public void expediaTitleCheck() {
test = extent.createTest("Title Check Test...");
exp.checkPageTitle();
test.fail("This Test is Failed!");
}
#AfterMethod
public void tearDown(ITestResult result)throws IOException {
if(result.getStatus() == ITestResult.FAILURE) {
String methodName ="<b>"+result.getMethod().getMethodName()+" : "+"FAILED"+"</b>";
String errorMsg = "<b>"+"REASON: "+" "+result.getThrowable().getMessage()+"</b>";
String failureScreenshot = Expedia_TC.captureScreen(driver, methodName);
test.log(Status.FAIL,MarkupHelper.createLabel(methodName,ExtentColor.RED));
test.log(Status.FAIL,errorMsg);
try {
test.addScreenCaptureFromPath(failureScreenshot);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
#AfterTest
public void endReport() {
extent.flush();
driver.quit();
}

Related

Why I need to add some delay while making concurrent request in streaming gRPC? (Java) to get output

#Test
public void testType() throws InterruptedException {
Integer num = 15;
String name = "Sahil";
Float percentage = 96.7f;
DOB dob = DOB.newBuilder().setDay(20).setMonth(8).setYear(2022).build();
ArrayList<Object> objects = new ArrayList<>(Arrays.asList(num,name,percentage,dob));
TypeRequest.Builder builder = TypeRequest.newBuilder();
StreamObserver<TypeResponse> typeResponseStreamObserver = new StreamObserver<TypeResponse>() {
#Override
public void onNext(TypeResponse typeResponse) {
System.out.println(
"Type : " + typeResponse.getType()
);
}
#Override
public void onError(Throwable throwable) {
System.out.println("Error : "+throwable);
}
#Override
public void onCompleted() {
System.out.println("Finished all requests");
}
};
StreamObserver<TypeRequest> typeRequestStreamObserver = this.calculatorServiceStub.getType(typeResponseStreamObserver);
for(Object obj : objects){
if (obj instanceof Integer){
builder.setNum((Integer) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof String) {
builder.setName((String) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof Float) {
builder.setFNum((Float) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof DOB) {
builder.setDob((DOB) obj);
typeRequestStreamObserver.onNext(builder.build());
}
// --------------------------------------------
Thread.sleep(500);
// --------------------------------------------
}
typeRequestStreamObserver.onNext(builder.clearType().build());
typeRequestStreamObserver.onCompleted();
}
If I did not add any delay then the output console is just blank. Testing with tools like BloomRPC and Postman it works fine,
but for this I don't know why this is happening?
Any little help will be very helpful. I appreciate it.

Circuit Breaker with gRPC

In a REST service adding a circuit breaker with hystrix, I could do the following:
#HystrixCommand(fallbackMethod = "getBackupResult")
#GetMapping(value = "/result")
public ResponseEntity<ResultDto> getResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = service.parserRequest(someRequest);
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
public ResponseEntity<ResultDto> getBackupResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = new ResultDto();
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
Is there something similar I can do for the gRPC call?
public void parseRequest(ParseRequest request, StreamObserver<ParseResponse> responseObserver) {
try {
ParseResponse parseResponse = service.parseRequest(request.getSomeRequest());
responseObserver.onNext(parseResponse);
responseObserver.onCompleted();
} catch (Exception e) {
logger.error("Failed to execute parse request.", e);
responseObserver.onError(new StatusException(Status.INTERNAL));
}
}
I solved my problem by implementing the circuit-breaker on my client. I used the sentinel library
To react on exceptions ratio for example I added this rule:
private static final String KEY = "callGRPC";
private void callGRPC(List<String> userAgents) {
initDegradeRule();
ManagedChannel channel = ManagedChannelBuilder.forAddress(grpcHost, grpcPort).usePlaintext()
.build();
for (String userAgent : userAgents) {
Entry entry = null;
try {
entry = SphU.entry(KEY);
UserAgentServiceGrpc.UserAgentServiceBlockingStub stub
= UserAgentServiceGrpc.newBlockingStub(channel);
UserAgentParseRequest request = UserAgentRequest.newBuilder().setUserAgent(userAgent).build();
UserAgentResponse userAgentResponse = stub.getUserAgentDetails(request);
} catch (BlockException e) {
logger.error("Circuit-breaker is on and the call has been blocked");
} catch (Throwable t) {
logger.error("Exception was thrown", t);
} finally {
if (entry != null) {
entry.exit();
}
}
}
channel.shutdown();
}
private void initDegradeRule() {
List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule();
rule.setResource(KEY);
rule.setCount(0.5);
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
rule.setTimeWindow(60);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}

Explicit Wait for automating windows application using winappdriver

I am a newbie to Windows Application Driver and my project demands automating the desktop application, so I decided to use winappdriver as it is similar to selenium, on which I am pretty confident about using.
speaking of the issue,
Just wondering if there is a way to achieve explicit wait and implicit wait using winappdriver. Following is the code i used as part of my test cases, the test fails with an exception (NoSuchElementException), however, if I put a static wait in place instead of explicit wait, it works as expected.
//Driver Setup
public class OscBase {
public static WindowsDriver<WebElement> applicaitonSession, driver = null;
public static WindowsDriver<RemoteWebElement> desktopSession = null;
public static DesiredCapabilities capabilities, cap1, cap2;
public static ProcessBuilder pBuilder;
public static Process p;
public void startDriver() {
try {
pBuilder = new ProcessBuilder("C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe");
pBuilder.inheritIO();
p = pBuilder.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void stopDriver() {
p.destroy();
}
public void createDesktopSession() throws MalformedURLException {
cap1 = new DesiredCapabilities();
cap1.setCapability("app", "Root");
desktopSession = new WindowsDriver<RemoteWebElement>(new URL("http://localhost:4723"), cap1);
}
public void openApplication() throws InterruptedException, MalformedURLException {
if (driver == null) {
try {
capabilities = new DesiredCapabilities();
capabilities.setCapability("app",
"Appnamewithlocation");
applicaitonSession = new WindowsDriver<WebElement>(new URL("http://localhost:4723"),
capabilities);
} catch (Exception e) {
System.out.println("Application opened!!!");
} finally {
createDesktopSession();
}
Thread.sleep(8000L);
String handle = desktopSession.findElementByAccessibilityId("InstallerView5")
.getAttribute("NativeWindowHandle");
System.out.println(handle);
int inthandle = Integer.parseInt(handle);
String hexHandle = Integer.toHexString(inthandle);
//System.out.println(hexHandle);
cap2 = new DesiredCapabilities();
cap2.setCapability("appTopLevelWindow", hexHandle);
driver = new WindowsDriver<WebElement>(new URL("http://localhost:4723"), cap2);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
public boolean isDisplayed_SafeLoginNoBtn() {
wait = new WebDriverWait(driver, 40);
return wait.until(ExpectedConditions.visibilityOf(safeLoginNoBtn())).isDisplayed();
}
#Test
public void osc_Get_Data() throws InterruptedException, IOException {
//Thread.sleep(20000);
// Boolean value=oscLogin.safeLoginNoBtn().isDisplayed();
try {
Boolean value = oscLogin.isDisplayed_SafeLoginNoBtn();
System.out.println("IS displayed========>"+value);
if (value) {
oscLogin.click_safeLogin();
}
} catch (Exception e) {
System.out.println("Safe Login!!!!");
}
Of course yes, the WebDriverWait class will work. Here's an example
WebDriverWait waitForMe = new WebDriverWait();
WebDriverWait waitForMe = new WebDriverWait(session, new TimeSpan.Fromseconds(10));
var txtLocation = session.FindElementByName("Enter a location");
waitForMe.Until(pred => txtLocation.Displayed);
I've created a detailed course about UI Automation using WinAppDriver and C# .Net. I'll be publishing it in a few days. Do let me know if you're interested :)

Android New Version Available - App Update Dialog Using Json From Own Server

I want to show dialogue when new version is available.
I want to make a json file into my web server, and I will manually update my app version in json file. and my app will parse this json file and will notify users and showing dialogue box to update my app from playstore link by clicking Update button.
I don't want to make this with firebase.
public class ForceUpdateAsync extends AsyncTask<String, String, JSONObject>{
private String latestVersion;
private String currentVersion;
private Context context;
public ForceUpdateAsync(String currentVersion, Context context){
this.currentVersion = currentVersion;
this.context = context;
}
#Override
protected JSONObject doInBackground(String... params) {
try
{
latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id="+context.getPackageName()+"&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
} catch (IOException e) {
e.printStackTrace();
}
return new JSONObject();
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null){
if(!currentVersion.equalsIgnoreCase(latestVersion)){
// Toast.makeText(context,"update is available.",Toast.LENGTH_LONG).show();
if(!(context instanceof SplashActivity)) {
if(!((Activity)context).isFinishing()){
showForceUpdateDialog();
}
}
}
}
super.onPostExecute(jsonObject);
}
public void showForceUpdateDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context,
R.style.DialogDark));
alertDialogBuilder.setTitle(context.getString(R.string.youAreNotUpdatedTitle));
alertDialogBuilder.setMessage(context.getString(R.string.youAreNotUpdatedMessage) + " " + latestVersion + context.getString(R.string.youAreNotUpdatedMessage1));
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
dialog.cancel();
}
});
alertDialogBuilder.show();
}
}
after that in your splash activity just use this code
public void forceUpdate()
{
PackageManager packageManager = this.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(getPackageName(),0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String currentVersion = packageInfo.versionName;
new ForceUpdateAsync(currentVersion,BaseActivity.this).execute();
}

BlackBerry - Exception when sending SMS

The code below should send a text message to a mobile number. It currently fails to work properly.
When the program attempts a message, the following error is reported:
Blocking operation not permitted on event dispatch thread
I created a separate thread to execute the SMS code, but I am still observing the same exception.
What am I doing wrong?
class DummyFirst extends MainScreen {
private Bitmap background;
private VerticalFieldManager _container;
private VerticalFieldManager mainVerticalManager;
private HorizontalFieldManager horizontalFldManager;
private BackGroundThread _thread;
CustomControl buttonControl1;
public DummyFirst() {
super();
LabelField appTitle = new LabelField("Dummy App");
setTitle(appTitle);
background = Bitmap.getBitmapResource("HomeBack.png");
_container = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL
| Manager.NO_VERTICAL_SCROLLBAR) {
protected void paint(Graphics g) {
// Instead of these next two lines, draw your bitmap
int y = DummyFirst.this.getMainManager()
.getVerticalScroll();
g.clear();
g.drawBitmap(0, 0, background.getWidth(), background
.getHeight(), background, 0, 0);
super.paint(g);
}
protected void sublayout(int maxWidth, int maxHeight) {
int width = background.getWidth();
int height = background.getHeight();
super.sublayout(width, height);
setExtent(width, height);
}
};
mainVerticalManager = new VerticalFieldManager(
Manager.NO_VERTICAL_SCROLL |
Manager.NO_VERTICAL_SCROLLBAR) {
protected void sublayout(int maxWidth, int maxHeight) {
int width = background.getWidth();
int height = background.getHeight();
super.sublayout(width, height);
setExtent(width, height);
}
};
HorizontalFieldManager horizontalFldManager =
new HorizontalFieldManager(Manager.USE_ALL_WIDTH);
buttonControl1 = new CustomControl("Send", ButtonField.CONSUME_CLICK,
83, 15);
horizontalFldManager.add(buttonControl1);
this.setStatus(horizontalFldManager);
FieldListener listner = new FieldListener();
buttonControl1.setChangeListener(listner);
_container.add(mainVerticalManager);
this.add(_container);
}
class FieldListener implements FieldChangeListener {
public void fieldChanged(Field f, int context) {
if (f == buttonControl1) {
_thread = new BackGroundThread();
_thread.start();
}
}
}
private class BackGroundThread extends Thread {
public BackGroundThread() {
/*** initialize parameters in constructor *****/
}
public void run() {
// UiApplication.getUiApplication().invokeLater(new Runnable()
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
MessageConnection msgConn =
(MessageConnection) Connector
.open("sms://:0");
Message msg = msgConn
.newMessage(
MessageConnection.TEXT_MESSAGE);
TextMessage txtMsg = (TextMessage) msg;
String msgAdr = "sms://+919861348735";
txtMsg.setAddress(msgAdr);
txtMsg.setPayloadText("Test Message");
// here exception is thrown
msgConn.send(txtMsg);
System.out.println("Sending" +
" SMS success !!!");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} // run
});
}
}
public boolean onClose() {
System.out.println("close event called, request to be" +
" in the backgroud....");
UiApplication.getUiApplication().requestBackground();
return true;
}
}
Dec 14, 2009 Stella answered their own question:
I resolved this issue by creating a separate thread and then not using Port etc.
Here it is:
SMSThread smsthread = new SMSThread("Some message",mobNumber);
smsthread.start();
class SMSThread extends Thread {
Thread myThread;
MessageConnection msgConn;
String message;
String mobilenumber;
public SMSThread( String textMsg, String mobileNumber ) {
message = textMsg;
mobilenumber = mobileNumber;
}
public void run() {
try {
msgConn = (MessageConnection) Connector.open("sms://+"+ mobilenumber);
TextMessage text = (TextMessage) msgConn.newMessage(MessageConnection.TEXT_MESSAGE);
text.setPayloadText(message);
msgConn.send(text);
msgConn.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}

Resources