Use code generation for executing generic tests - java

I think I have an interesting question and PERHAPS there is already the answer which is still a secret for me, so I hope to get some helps from expers. :)
So here is the thing:
I work for the test/validation team to test our Java API and basically my job is to follow test plan and write the test code. After writing that for more than two months, I find the codes are really similar. For example:
To test function could return expected result or throw exception correctly, we may need write several .java to run.
1.java set up server connection, connect client and send request, initiate variables with correct values and pass them to the function A, catch the answer and analyse it
2.java set up server connection, connect client and send request, initiate all variables with correct values but one with bad value and pass them to function A, catch the answer and analyse it
3.java set up server connection, connect client and send request, initiate all variables with correct values but two with bad values and pass them to function A, catch the answer and analyse it
so you see in three java test files, the most part of them are the same or similar enough and even copy/paste make the job boring and possible to be wrong.
I wonder whether or not I could define test code corresponding different behavior, then for every test java file, I define a text including the behavior and then a mother class who is in charge of loading the text file and assembling the final test java file according to the text file?
Like this:
Text File:
1) set up server
2) connect client
3) send request
4) initiate variables with correct values
5) initiate variables with correct values but one with bad value
6) initiate variables with correct values but two with bad values
7) catch the result and analyse it
Mother.java
1) load Text file
2) create a son.java
3) find the code corresponding the Text file and write them to son.java
Then the coder open son.java at IDE to check syntax, or import or anything conflict then run it.
Is my idea realizable or not? Is there already something similar?
Any information would be appreciated, thanks a millions in advance!

Honestly, this does not sound like a good use case for code generation. Instead of generating a class for each test case, you should implement a more general testing utility which takes the required input as its data and executes the generic testing code based on this data.
From what you write, this would for example be something like a simple base class for a JUnit test:
abstract class AbstractServerDependantTest {
protected Server server;
protected Client client;
#Before
public void setUp() {
server = new Server();
server.start();
client = new Client();
client.connectTo(server);
}
#After
public void tearDpwm() {
client.disconnect();
server.shutDown();
}
}
Now you can write three test classes which inherit from this AbstractServerDependantTest without copy pasting your code.

Related

Access .tlb from JAVA

Currently trying to access a type library file from JAVA, I have tried the following with corresponding errors:
1- Com2Java: I receive this Error Each time I try to connect to my application:
Minidumps are not enabled by default on client versions of Windows
2- Com4j: It produces only interfaces and Couldn't understand how to use them (I can't find any classes, just interfaces)
3- After a small search, found out about Visual J++ but couldnt download it coz it was discontnued.
Could anyone give advice?
Thank you
I have not used Com2Java or Com4j before, but a long time ago I used a library called JavaCOMBridge (https://sourceforge.net/projects/jacob-project/).
The version of JavaCOMBridge I used cannot handle multiple inheritance, and I don't see how there can be a good way to do it.
Forget about Visual J++. It's an abomination created by Microsoft and was sued into oblivion.
If you are experienced in both C and Java, and the amount of APIs you have to bridge is not large, I'd recommend using JNI directly.
Edit
Here's an example using Excel:
package test;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class JaCoBTest {
public static void main(String[] args) {
String EXCEL_FILE = "FullPathOfAnExcelFile.xlsx";
// Using Excel as an example
ActiveXComponent app = new ActiveXComponent("Excel.Application");
// Modify a property, to show Excel window
app.setProperty("Visible", true);
// Get Excel workbook object
Dispatch workbook = app.getProperty("Workbooks").toDispatch();
// Call method, to open an Excel file
Dispatch.call(workbook, "Open", new Variant(EXCEL_FILE), new Variant("1"));
// Wait for 5 seconds
try {
Thread.sleep(1000);
} catch (InterruptedException iex) {
iex.printStackTrace();
}
// Close Excel without saving
workbook.call(workbook, "Close");
// Close is supposed to have three optional parameteters, but the line below is not working
//workbook.call(workbook, "Close", new Variant(false), Variant.DEFAULT, Variant.DEFAULT);
// Close Excel
Dispatch.call(app, "Quit");
}
}
There is one problem in the above code - I cannot get optional parameters to work. The function Workbook.Close is supposed to take three optional parameters, but the call always fail with invalid number of parameters.
I've also located the web page I used back then:
http://danadler.com/jacob/
The above page contains a link to a FAQ but it's slightly outdated.

Java method that writes to file does nothing when invoked from a JSP

Hey, all! I have a class method who's primary function is to get a Map object, which works fine; however, it's an expensive operation that doesn't need to be done every time, so I'd like to have the results stored in an XML file using JAXB, to be read from for the majority of calls and updated infrequently.
When I run a class that calls it out of NetBeans the file is created no problem with exactly what I want -- but when I have my JSP call the method nothing happens whatsoever, even though the rest of the information is passed normally. I have the feeling it's somehow lacking write privileges, but the file is just in the root directory so I'm not sure what I'm missing. Thanks for the help!
The code looks roughly like this:
public class DataHandler() {
...
public void config() {
MapHolder bucket = new MapHolder();
MapExporter exp = new MapExporter();
Map map = makeMap();
bucket.setMap(map);
exp.exportMap(bucket);
}
}
And then the JSP has a javabean of Datahandler, and this line:
databean.config();
It's probably a tad more fragmented than it needs to be; the whole bucket rigamarole was because I was stumbling trying to learn how to write a map to an xml file. Mapholder is just a class that I wrap around the map, and MapExporter just uses a JAXB marshaller, and it all does work properly when run from NetBeans.
OK turns out I'm just dumb; everything was working fine, the file was just being stored in a folder at the localhost location. Whoops! That'd be my inexperience with web development at work.

Load java function in Lua

Simple QUESTION : Are there ways to run or load java functions inside Lua?
I am trying to create a phone application that transfers files between server and client using Lua. The server uses Java while client uses Lua.
this is a lua function that receives file
function UDPClientModule.receiveFile()
local data, status
local chunks = {}
while true do
data, status = udp:receive()
print("status: ", status)
if data ~= nil then
table.insert(chunks, data)
--the filename is the last chunk to be received
if string.match(data, ".jpg") then
-- but strangely returns true
break
end
end
socket.sleep(0.5)
end
--combineAndOpenImage(t)
end
No problems so far. However, the chunks sent by the server are encapsulated in a class like this:
public class FileChunk {
private List<Data> dataList;
//functions below
}
public class Data{
private byte[] fileData;
// functions and adding file headers below
} // then UDPServer.java sends bytes of FileChunk
Because of this, packets received by the lua function are strange which also results in string.match(data, ".jpg") returning true. So I want to run java files (eg. UDPClient.java) in order to receive and decipher the chunks, instead of lua.
I don't want to change the server nor migrate the client language to java. I haven't found any resources about this so I need help.
You would need to create a wrapper library, such as the ones in C. I do not know how, but I hope this provides you a sense of direction.

Handling non-fatal errors in Java

I've written a program to aid the user in configuring 'mechs for a game. I'm dealing with loading the user's saved data. This data can (and some times does) become partially corrupt (either due to bugs on my side or due to changes in the game data/rules from upstream).
I need to be able to handle this corruption and load as much as possible. To be more specific, the contents of the save file are syntactically correct but semantically corrupt. I can safely parse the file and drop whatever entries that are not semantically OK.
Currently my data parser will just show a modal dialog with an appropriate warning message. However displaying the warning is not the job of the parser and I'm looking for a way of passing this information to the caller.
Some code to show approximately what is going on (in reality there is a bit more going on than this, but this highlights the problem):
class Parser{
public void parse(XMLNode aNode){
...
if(corrupted) {
JOptionPane.showMessageDialog(null, "Corrupted data found",
"error!", JOptionPane.WARNING_MESSAGE);
// Keep calm and carry on
}
}
}
class UserData{
static UserData loadFromFile(File aFile){
UserData data = new UserData();
Parser parser = new Parser();
XMLDoc doc = fromXml(aFile);
for(XMLNode entry : doc.allEntries()){
data.append(parser.parse(entry));
}
return data;
}
}
The thing here is that bar an IOException or a syntax error in the XML, loadFromFile will always succeed in loading something and this is the wanted behavior. Somehow I just need to pass the information of what (if anything) went wrong to the caller. I could return a Pair<UserData,String> but this doesn't look very pretty. Throwing an exception will not work in this case obviously.
Does any one have any ideas on how to solve this?
Depending on what you are trying to represent, you can use a class, like SQLWarning from the java.sql package. When you have a java.sql.Statement and call executeQuery you get a java.sql.ResultSet and you can then call getWarnings on the result set directly, or even on the statement itself.
You can use an enum, like RefUpdate.Result, from the JGit project. When you have a org.eclipse.jgit.api.Git you can create a FetchCommand, which will provide you with a FetchResult, which will provide you with a collection of TrackingRefUpdates, which will each contain a RefUpdate.Result enum, which can be one of:
FAST_FORWARD
FORCED
IO_FAILURE
LOCK_FAILURE
NEW
NO_CHANGE
NOT_ATTEMPTED
REJECTED
REJECTED_CURRENT_BRANCH
RENAMED
In your case, you could even use a boolean flag:
class UserData {
public boolean isCorrupt();
}
But since you mentioned there is a bit more than that going on in reality, it really depends on your model of "corrupt". However, you will probably have more options if you have a UserDataReader that you can instantiate, instead of a static utility method.

Java File Transfer API

I need to transfer files to my web server for processing and I'd like to do it in a generic way if possible.
I need to be able to transfer files from the following protocols at a minimum (with more to follow eventually):
HTTP
FTP
SCP
I'd really like to be able to send files to SMTP also
So my question, is there a toolkit available that does this already? If so, it must be open source as this is part of an open source project.
If there isn't a toolkit that already does this, what is the best way to structure an interface that will handle most file transfers?
I've thought about something like this:
public interface FileTransfer {
public void connect(URL url, String userid, String password);
public void disconnect();
public void getFile(String sourceFile, File destFile);
public void putFile(File sourceFile, File destFile);
}
And then a Factory that takes the source URL or protocol and instantiates the correct file handler.
Apache commons VFS speaks to this problem, although a quick check didn't show that it will do SCP or SMTP. Commons NET does SMTP, but I don't know that you could get the common interface out of the box. For SCP, here are some possibilities.
The bottom line seems to be to check out the VFS implementation and see if it does something for you, perhaps you can extend it for different protocols. If it isn't appropriate, regarding your interface, you are probably going to want all remote file references to be Strings rather than File objects, and specifically a string representing a URI pointing to the remote location and telling you what protocol to use.
I'm working at a problem very similar to yours, I couldn't find any open source solution so I'm trying to sketch a solution myself. This is what I've come up with.
I think you should represent inputSources and outputSources as different things, like
public interface Input{
abstract InputStream getFileInputStream();
abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for Blob on db etc)
public interface Output{
abstract OutputStream getOutputStream();
abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for mailing the file etc)
Then you should have a Movement to describe which input should go to which output.
class Movement{
String inputId;
String outputId;
}
A class to describe the list of Movement to make.
class MovementDescriptor{
public addMovement(Movement a);
public Movement[] getAllMovements();
}
And then a class to perform the work itself.
class FileMover{
HashMap<String,Input> inputRegistry;
HashMap<String,Output> outputRegistry;
addInputToRegistry(Input a ){
inputRegistry.put(a.getId(),a);
}
addOutputToRegistry(Output a){
outputRegistry.put(a.getId(),a);
}
transferFiles(MovementDescriptor movementDescriptor){
Movement[] movements =movementDescriptor.getAllMovements();
foreach (Movement movement: movements){
//get the input Id
//find it in the registry and retrieve the associated InputStream
//get the output Id
//find it in the registry and retrieve the associated OutputStream
//copy the stream from the input to the output (you may want to use a temporary file in between)
}
}
}
The code that would use this would operate like this:
FileMover fm=new FileMover();
//Register your sources and your destinations
fm.addInputToRegistry(input);
fm.addOutputToRegistry(output)
// each time you have to make a movement create a MovementDescriptor and call
fm.transferFiles(movementDescriptor)
If you would like to exchange by mail our views on the subject, just send me an e mail at (my nickname)#gmail dot com.
NOTE: The code is just a sketch :-)
I think JSch implements SCP, so that covers that one.
please make use of JCraft . Open "sftp" channel and try that.

Categories

Resources