I am very new to Oracle Application Testing Suite(OATS).In my project I need to automate the file uploading functionality. That is , after clicking browse..button , file explorer will open.
My question is how to aytomate this scenario.
I serached many websites and in youtube but did not get any useful. Please help as it is important in my current project. Any help will be appreciated.
Most of file upload based on windows objects .
Open Script doesn't support windows based object identification for that we have to use external plugin or jar files
best suitable one is RobotClass .
Here is the complete example
http://www.testinghive.com/how-to-perform-file-upload-in-oats-tool/
try
{
Robot robot = new Robot();
robot.delay(200);
upload_parseChars("C:\\testDemo.xlsx", robot);
robot.delay(200);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
catch (AWTException e) {
e.printStackTrace();
}
public void upload_parseChars(String letter, Robot robot) throws AbstractScriptException {
for (int i = 0; i < letter.length(); i++) {
//info("inside uf_Vik_parseChars method ");
char chary = letter.charAt(i);
//info("Current character = "+letter.charAt(i));
upld_typeCharacter(Character.toString(chary), robot);
}
}
public void upld_typeCharacter(String letter, Robot robot) throws AbstractScriptException {
// info("Pressed event ");
if (Character.isLetterOrDigit(letter.charAt(0))) {
try {
boolean upperCase = Character.isUpperCase(letter.charAt(0));
String variableName = "VK_" + letter.toUpperCase();
KeyEvent ke = new KeyEvent(new JTextField(), 0, 0, 0, 0, ' ');
#SuppressWarnings("rawtypes")
Class clazz = ke.getClass();
Field field = clazz.getField(variableName);
int keyCode = field.getInt(ke);
robot.delay(80);
if (upperCase)
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
if (upperCase)
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (Exception e) {
System.out.println(e);
}
} else {
if (letter.equals("!")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("$")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("%")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("^")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("&")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("*")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("=")) {
robot.keyPress(KeyEvent.VK_EQUALS);
robot.keyRelease(KeyEvent.VK_EQUALS);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals("/")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("\\")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("_")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(":")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(";")) {
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
} else if (letter.equals(",")) {
robot.keyPress(KeyEvent.VK_COMMA);
robot.keyRelease(KeyEvent.VK_COMMA);
} else if (letter.equals("-")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("?")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals(".")) {
robot.keyPress(KeyEvent.VK_PERIOD);
robot.keyRelease(KeyEvent.VK_PERIOD);
}
}
}
THE download dialog and upload dialog is supported. try to record one and try related
I have a WebAPI2 mvc app where I'm doing Get/Post to another api. My code looks like below
public Task<SomeEntity> AddAsync(SomeEntity someEntity)
{
try
{
var response = apiService.PostItem(url, someEntity);
if (response == null || response!="Successful")
{
throw new InvalidOperationException(response);
}
}
catch (Exception ex)
{
_logger.Error("Error " + ex.Message);
// how to return this error or exception;
}
return Task.FromResult(someEntity);
}
If the call to the internal api return an exception string then I need to forward it from this method call. Any ideas how can I do it? thanks
You can use IHttpActionResult or HttpResponseMessage as your return type and return proper HTTP-Status codes. In case of exception you can return [if you return IHttpActionResult ]
public IHttpActionResult Error()
{
var error = new HttpError();
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));
}
or as in your example, throw HttpResponseException with appropriate status code.
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
}
else
{
return item;
}
}
I have got a problem with back button in MVVMCross when using zxing barcode scanner. Unfortunetly, when I press back button, there is an error: Java.Lang.NullPointerException: Attempt to invoke virtual method 'long android.graphics.Paint.getNativeInstance()' on a null object reference
When I comment metohs scan() weverything is ok.
Someone know what's going wrong?
This is my fragment scann view class:
public class ScannView : MvxFragmentActivity, IBarcodeFragmentOptions
{
protected ScannViewModel MainViewModel
{
get { return ViewModel as ScannViewModel; }
}
public static ZXingScannerFragment scanFragment;
protected override void OnResume()
{
base.OnResume();
try
{
if (scanFragment == null)
{
scanFragment = new ZXingScannerFragment();
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.frameScanner, scanFragment)
.Commit();
}
scan();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
protected override void OnPause()
{
try
{
scanFragment?.StopScanning();
base.OnPause();
}catch(Exception ex)
{
Console.WriteLine(ex);
}
}
protected override void OnRestart()
{
base.OnRestart();
}
public void ToogleFlashLight(bool on)
{
if (scanFragment != null)
scanFragment.SetTorch(on);
}
public void scan()
{
try
{
// var results = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.Camera);
// var status = results[Plugin.Permissions.Abstractions.Permission.Camera];
// if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
// {
var opts = new MobileBarcodeScanningOptions
{
PossibleFormats = new List<ZXing.BarcodeFormat> {
ZXing.BarcodeFormat.QR_CODE
},
CameraResolutionSelector = availableResolutions => {
foreach (var ar in availableResolutions)
{
Console.WriteLine("Resolution: " + ar.Width + "x" + ar.Height);
}
return null;
}
};
scanFragment?.StartScanning(opts,result =>
{
if (result == null || string.IsNullOrEmpty(result.Text))
{
RunOnUiThread(() => Toast.MakeText(this, "Anulowanie skanowanie", ToastLength.Long).Show());
return;
}
MainViewModel.ScannedCode = result.Text; //ChangePropertyToEmpty();
RunOnUiThread(() => Toast.MakeText(this, "Zeskanowano: " + result.Text, ToastLength.Short).Show());
});
// }
}catch(Exception ex)
{
Debug.WriteLine(ex);
}
}
protected override void OnViewModelSet()
{
MobileBarcodeScanner.Initialize(Application);
base.OnViewModelSet();
SetContentView(Resource.Layout.layout_scann);
}
}
And here in my viewmdoel I have simple method to close current viewmodel:
public void ButtonBackClick()
{
Close(this);
}
When attempting to validate a journal I use the LedgerJournalEngine ErrorExists for each voucher in the journal. For some reason it doesn't catch all errors in the code but if I use the validate button in the client the errors are in the info log.
Is there a better way to validate a voucher in a journal?
changecompany(ledgerJournalTable.dataAreaId)
{
ledgerJournalCheckPost = LedgerJournalCheckPost::newLedgerJournalTable(ledgerJournalTable,NoYes::Yes,NoYes::No);
lje = LedgerJournalEngine::construct(ledgerJournalTable.JournalType);
lje.newJournalActive(ledgerJournalTable,true);
ledgerJournalCheckPost.parmLedgerJournalEngine(lje);
try
{
ledgerJournalCheckPost.run();
}
catch
{
ledgerJournalCheckPost.validate();
while select ledgerJournalTrans where ledgerJournalTrans.JournalNum == ledgerJournalTable.JournalNum
{
if(lje.errorExists(ledgerJournalTrans.Voucher))
{
errors.addError(lje.errorLog(ledgerJournalTrans.Voucher),ledgerJournalTrans.RecId);
}
}
}
}
So this is what I have come up with, so far it seems to be working as expected. If anyone has a better way please let me know.
changecompany(ledgerJournalTable.dataAreaId)
{
ledgerJournalCheckPost = LedgerJournalCheckPost::newLedgerJournalTable(ledgerJournalTable,NoYes::No);
lje = LedgerJournalEngine::construct(ledgerJournalTable.JournalType);
lje.newJournalActive(ledgerJournalTable,true);
ledgerJournalCheckPost.parmLedgerJournalEngine(lje);
try
{
ledgerJournalCheckPost.run();
while select ledgerJournalTrans where ledgerJournalTrans.JournalNum == ledgerJournalTable.JournalNum
{
if(lje.errorInJournal() || ledgerJournalCheckPost.numOfErrorsInList()>0)
{
errors.addError(lje.errorLog(ledgerJournalTrans.Voucher),ledgerJournalTrans.RecId);
}
}
ledgerJournalCheckPost.parmPost(NoYes::Yes);
ledgerJournalCheckPost.run();
}
catch
{
ledgerJournalCheckPost.validate();
while select ledgerJournalTrans where ledgerJournalTrans.JournalNum == ledgerJournalTable.JournalNum
{
if(lje.errorInJournal() || ledgerJournalCheckPost.numOfErrorsInList()>0)
{
errors.addError(lje.errorLog(ledgerJournalTrans.Voucher),ledgerJournalTrans.RecId);
}
}
}
ledgerJournalCheckPost = null;
lje = null;
ledgerJournalTrans = null;
ledgerJOurnalTable = null;
}
return errors;
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want to refactor this mumbo jumbo of a method to make it more readible, it has way to many nested IF's for my liking.
How would you refactor this?
public static void HandleUploadedFile(string filename)
{
try
{
if(IsValidFileFormat(filename)
{
int folderID = GetFolderIDFromFilename(filename);
if(folderID > 0)
{
if(HasNoViruses(filename)
{
if(VerifyFileSize(filename)
{
// file is OK
MoveToSafeFolder(filename);
}
else
{
DeleteFile(filename);
LogError("file size invalid");
}
}
else
{
DeleteFile(filename);
LogError("failed virus test");
}
}
else
{
DeleteFile(filename);
LogError("invalid folder ID");
}
}
else
{
DeleteFile(filename);
LogError("invalid file format");
}
}
catch (Exception ex)
{
LogError("unknown error", ex.Message);
}
finally
{
// do some things
}
}
I would reverse the conditions in the test to if bad then deleteAndLog as the example below. This prevent nesting and puts the action near the test.
try{
if(IsValidFileFormat(filename) == false){
DeleteFile(filename);
LogError("invalid file format");
return;
}
int folderID = GetFolderIDFromFilename(filename);
if(folderID <= 0){
DeleteFile(filename);
LogError("invalid folder ID");
return;
}
...
}...
Guard clauses.
For each condition, negate it, change the else block into the then block, and return.
Thus
if(IsValidFileFormat(filename)
{
// then
}
else
{
// else
}
Becomes:
if(!IsValidFileFormat(filename)
{
// else
return;
}
// then
If you are not against using exceptions, you could handle the checks without nesting.
Warning, air code ahead:
public static void HandleUploadedFile(string filename)
{
try
{
int folderID = GetFolderIDFromFilename(filename);
if (folderID == 0)
throw new InvalidFolderException("invalid folder ID");
if (!IsValidFileFormat(filename))
throw new InvalidFileException("invalid file format!");
if (!HasNoViruses(filename))
throw new VirusFoundException("failed virus test!");
if (!VerifyFileSize(filename))
throw new InvalidFileSizeException("file size invalid");
// file is OK
MoveToSafeFolder(filename);
}
catch (Exception ex)
{
DeleteFile(filename);
LogError(ex.message);
}
finally
{
// do some things
}
}
One possible approach is to have single if statements that check for when the condition isn't true. Have a return for each one of these checks. This turns your method into a sequence of 'if' blocks instead of a nest.
There's not a lot to refactor here, as you keep the 3 tests separately due to the fact that the error messages relate to the test performed. You could opt for having the test methods report back the error to log so you don't have them in the if/else tree, which could make things simpler abit as you then could simply test for an error and log it + delete the file.
In David Waters reply, I don't like the repeated DeleteFile LogError pattern. I would either write a helper method called DeleteFileAndLog(string file, string error) or I would write the code like this:
public static void HandleUploadedFile(string filename)
{
try
{
string errorMessage = TestForInvalidFile(filename);
if (errorMessage != null)
{
LogError(errorMessage);
DeleteFile(filename);
}
else
{
MoveToSafeFolder(filename);
}
}
catch (Exception err)
{
LogError(err.Message);
DeleteFile(filename);
}
finally { /* */ }
}
private static string TestForInvalidFile(filename)
{
if (!IsValidFormat(filename))
return "invalid file format.";
if (!IsValidFolder(filename))
return "invalid folder.";
if (!IsVirusFree(filename))
return "has viruses";
if (!IsValidSize(filename))
return "invalid size.";
// ... etc ...
return null;
}
It's the elses above that throw my eye. Here's an alternative, inside the try {}
You can make this even shorter by returning after MoveToSafeFolder (Even though you're returning the finally block will be executed.) Then you don't need to assign an empty string to errorMessage, and you don't need to check is errorString empty before deleting the file and logging the message). I didn't do it here because many find early returns offensive, and I'd agree in this instance, since having the finally block execute after the return is unintuitive for many people.
Hope this helps
string errorMessage = "invalid file format";
if (IsValidFileFormat(filename))
{
errorMessage = "invalid folder ID";
int folderID = GetFolderIDFromFilename(filename);
if (folderID > 0)
{
errorMessage = "failed virus test";
if (HasNoViruses(filename))
{
errorMessage = "file size invalid";
if (VerifyFileSize(filename))
{
// file is OK
MoveToSafeFolder(filename);
errorMessage = "";
}
}
}
}
if (!string.IsNullOrEmpty(errorMessage))
{
DeleteFile(filename);
LogError(errorMessage);
}
I would to something like this:
public enum FileStates {
MoveToSafeFolder = 1,
InvalidFileSize = 2,
FailedVirusTest = 3,
InvalidFolderID = 4,
InvalidFileFormat = 5,
}
public static void HandleUploadedFile(string filename) {
try {
switch (Handledoc(filename)) {
case FileStates.FailedVirusTest:
deletefile(filename);
logerror("Virus");
break;
case FileStates.InvalidFileFormat:
deletefile(filename);
logerror("Invalid File format");
break;
case FileStates.InvalidFileSize:
deletefile(filename);
logerror("Invalid File Size");
break;
case FileStates.InvalidFolderID:
deletefile(filename);
logerror("Invalid Folder ID");
break;
case FileStates.MoveToSafeFolder:
MoveToSafeFolder(filename);
break;
}
}
catch (Exception ex) {
logerror("unknown error", ex.Message);
}
}
private static FileStates Handledoc(string filename) {
if (isvalidfileformat(filename)) {
return FileStates.InvalidFileFormat;
}
if ((getfolderidfromfilename(filename) <= 0)) {
return FileStates.InvalidFolderID;
}
if ((HasNoViruses(filename) == false)) {
return FileStates.FailedVirusTest;
}
if ((VerifyFileSize(filename) == false)) {
return FileStates.InvalidFileSize;
}
return FileStates.MoveToSafeFolder;
}
How about this?
public static void HandleUploadedFile(string filename)
{
try
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return; }
// --------------------------------------------------------
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
or, even better, ... this:
public static void HandleUploadedFile(string filename)
{
try
{
if(ValidateUploadedFile(filename))
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private bool ValidateUploadedFile(string fileName)
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return false; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return false; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return false; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return false; }
// ---------------------------------------------------------------
return true;
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
NOTE: You shouldn't be catching and swallowing generic Exception without rethrowing it...