Testing the namespace - google-app-engine

In my app I have a method that uses one of its parameters to set the namespace. The code works but when I try to run tests on it I get a NullPointerException at NamespaceManager.set().
public String create(Bar bar) {
NamespaceManager.set(bar.getFoo.toString());
// more code
return NamespaceManager.get();
}
I have also tried using void as return type, but the error was the same.
I now wonder if this error comes from an error in my code or is it impossible to access the NamespaceManager in a unit test.
Edit
The test code:
#Before
public void before() {
Bar bar = new Bar();
bar.setFoo(1L);
CSDatastoreService csDatastore = Mockito.mock(CSDatastoreServiceImpl.class);
SController ctrl = new SController(csDatastore);
}
#Test
public void createSetsNamaspaceToFooOfBar() {
Assert.assertSame(ctrl.create(bar), bar.getFoo().toString());
}

Create an instance of com.google.appengine.tools.development.testing.LocalServiceTestHelper and call setup() before making any calls to the NamespaceManager in your unit tests.
example
public final static LocalServiceTestHelper helper = new LocalServiceTestHelper(
new LocalUserServiceTestConfig(),
new LocalDatastoreServiceTestConfig()
.setDefaultHighRepJobPolicyUnappliedJobPercentage(100.0f)
.setNoIndexAutoGen(true));
And further down :
#Before
public void setup() {
helper.setUp();
}

Related

Flink streaming example that generates its own data

Earlier I asked about a simple hello world example for Flink. This gave me some good examples!
However I would like to ask for a more ‘streaming’ example where we generate an input value every second. This would ideally be random, but even just the same value each time would be fine.
The objective is to get a stream that ‘moves’ with no/minimal external touch.
Hence my question:
How to show Flink actually streaming data without external dependencies?
I found how to show this with generating data externally and writing to Kafka, or listening to a public source, however I am trying to solve it with minimal dependence (like starting with GenerateFlowFile in Nifi).
Here's an example. This was constructed as an example of how to make your sources and sinks pluggable. The idea being that in development you might use a random source and print the results, for tests you might use a hardwired list of input events and collect the results in a list, and in production you'd use the real sources and sinks.
Here's the job:
/*
* Example showing how to make sources and sinks pluggable in your application code so
* you can inject special test sources and test sinks in your tests.
*/
public class TestableStreamingJob {
private SourceFunction<Long> source;
private SinkFunction<Long> sink;
public TestableStreamingJob(SourceFunction<Long> source, SinkFunction<Long> sink) {
this.source = source;
this.sink = sink;
}
public void execute() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<Long> LongStream =
env.addSource(source)
.returns(TypeInformation.of(Long.class));
LongStream
.map(new IncrementMapFunction())
.addSink(sink);
env.execute();
}
public static void main(String[] args) throws Exception {
TestableStreamingJob job = new TestableStreamingJob(new RandomLongSource(), new PrintSinkFunction<>());
job.execute();
}
// While it's tempting for something this simple, avoid using anonymous classes or lambdas
// for any business logic you might want to unit test.
public class IncrementMapFunction implements MapFunction<Long, Long> {
#Override
public Long map(Long record) throws Exception {
return record + 1 ;
}
}
}
Here's the RandomLongSource:
public class RandomLongSource extends RichParallelSourceFunction<Long> {
private volatile boolean cancelled = false;
private Random random;
#Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
random = new Random();
}
#Override
public void run(SourceContext<Long> ctx) throws Exception {
while (!cancelled) {
Long nextLong = random.nextLong();
synchronized (ctx.getCheckpointLock()) {
ctx.collect(nextLong);
}
}
}
#Override
public void cancel() {
cancelled = true;
}
}

Passing data using dataprovider in PageObjectModel in TestNG

i have a scenario where in im calling a method(which has code to create workflow - defined in pages POM framework), i have written a generic method to get the data from excel file using dataProvider in testNG
Now i have a #Test method which perform the action of creating the workflow as below
#DataProvider(name="wf")
public static String[][] getExcelData() throws Exception{
ExcelReader read = new ExcelReader();
String filePath = "path of excelfile";
return read.getCellData(filePath, "Sheet1");
}
#Test(dataProviderClass = ExcelReader.class, dataProvider="wf")
public void testing(String workflow, String type, String unit){
System.out.println("-------------Test case started -------------");
System.out.println("Call to login to the application");
System.out.println("Navigating to Some Page");
System.out.println("Navigating to WorkflowPage");
SampleClass s = new SampleClass();
s.createWorkflow(workflow,type,unit);
System.out.println("-----'--------Test case Ended ----------------");
System.out.println();
}
public void createWorkflow(String wf, String wf, String unit){
System.out.println("Creating WF");
System.out.println(wf);
System.out.println(type);
System.out.println(unit);
System.out.println("CREATED wf");
}
now if i run the #Test fails after creating the 1st workflow, becoz the #test method is run again from beginning instead of creating multiple workflow's, for 'createWorkflow method.
Can you let me know how can i achieve this or a better solution.
#BeforeMethod
public void beforeMethod(){
System.out.println("Call to login to the application");
System.out.println("Navigating to Some Page");
System.out.println("Navigating to WorkflowPage");
}
#Test(dataProviderClass = ExcelReader.class, dataProvider="wf")
public void testing(String workflow, String type, String unit){
System.out.println("-------------Test case started -------------");
SampleClass s = new SampleClass();
s.createWorkflow(workflow,type,unit);
System.out.println("-----'--------Test case Ended ----------------");
System.out.println();
}
public void createWorkflow(String wf, String wf, String unit){
System.out.println("Creating WF");
System.out.println(wf);
System.out.println(type);
System.out.println(unit);
System.out.println("CREATED wf");
}

Unity3D - how to use arrays with custom inspector code?

I seem to be stuck in a catch 22 situation with the OnInspectorGUI method of Unity's UnityEditor class. I want to name array elements in the inspector for easy editing, currently I'm using, as per the documentation:
public override void OnInspectorGUI()
{
J_Character charScript = (J_Character)target;
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
}
In my J_Character script I initialise the aBaseStats array like so:
public float[] aBaseStats = new float[35];
The problem is that whenever I try to do anything in the editor (and thus OnInspectorGUI is called) I get an index out of range error pointing to the line
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
I'm guessing this is because my array is initialized on game start while the editor code is running all the time while developing.
How can I get round this situation?
Many thanks.
You have to initialize aBaseStats in an function that runs only once.
The code below is BAD:
public float[] aBaseStats = new float[35];
void Start(){
}
The code below is GOOD:
public float[] aBaseStats;
void Start(){
aBaseStats = new float[35];
}
Initialize it in an Editor callback function that runs once.
EDIT:
I don't know a Start callback function that will run before the OnInspectorGUI function(). The hack below should work.
public float[] aBaseStats;
bool initialized = false;
public override void OnInspectorGUI()
{
if (!initialized)
{
initialized = true;
aBaseStats = new float[35];
}
J_Character charScript = (J_Character)target;
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health",aBaseStats[0]);
}
As an addition to the answer by Programmer I would like to point you to the following:
http://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
This seems to be exactly what you are looking for in terms of functionality. (it runs the method even when playmode is not active)
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ExampleClass : MonoBehaviour {
public Transform target;
void Update() {
if (target)
transform.LookAt(target);
}
}

what's the difference between object and primitive type when using matchers in EasyMock

//service to mock
public interface ServiceToMock {
public void operateDouble(Double dbValue);
public void operateCar(Car car);
}
//class under test
public class ClassUnderTest {
ServiceToMock service;
public void operateDouble(Double dbValue){
service.operateDouble(dbValue);
}
public void operateObject(Car car){
service.operateCar(car);
}
}
//unit test class
#RunWith(EasyMockRunner.class)
public class TestEasyMockMatcherUnderTest {
#TestSubject
private final ClassUnderTest easyMockMatcherUnderTest = new ClassUnderTest();
#Mock
private ServiceToMock mock;
#Test
public void testOperateCar() {
//record
mock.operateCar(EasyMock.anyObject(Car.class));
EasyMock.expectLastCall();
// replay
EasyMock.replay(mock);
//matcher here...
easyMockMatcherUnderTest.operateObject(EasyMock.anyObject(Car.class));
//easyMockMatcherUnderTest.operateObject(new Car());
// verify
EasyMock.verify(mock);
}
#Test
public void testOperateDouble() {
// record
mock.operateDouble(EasyMock.anyDouble());
EasyMock.expectLastCall();
// replay
EasyMock.replay(mock);
easyMockMatcherUnderTest.operateDouble(EasyMock.anyDouble());
// verify
EasyMock.verify(mock);
}
}
As the above code has shown, I intent to test two methods(operateDouble, operateObject). But things are kinda weird since everything runs fine in the operateDouble block while the compiler complaints an "Illegal state exception: 1 matchers expected, 2 recored." when runnig operateObject. And if commentting the method operateDouble out, the compaint goes away..So what is the difference between Double and my custom object Car, as the Double can also be considered as an object. And why does codes in operateObject runs well when commenting operateDouble method out?
EasyMock.anyDouble and EasyMock.anyObject are not meant to be used in replay mode. They are used to setup your expectations in record mode.
Use this in your first test (testOperateCar):
easyMockMatcherUnderTest.operateObject(new Car());
and something like this in your second (testOperateDouble):
easyMockMatcherUnderTest.operateDouble(1.0);
By the way, you don't need to call EasyMock.expectLastCall. It is only useful if you expect a void method to be called multiple times, for example:
mock.operateCar(EasyMock.anyObject(Car.class));
EasyMock.expectLastCall().times(3);

TestNg Assert.AssertTrue Always returns False - Selenium Webdriver

I have a util function as below:
public static boolean isWebElementEnabled(WebElement element) {
try {
return element.isEnabled();
} catch (Exception exx) {
return false;
}
}
public static boolean chkForThisElement(WebElement myElement) {
try {
return myElement.isDisplayed();
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
}
I call it like this in the base class:
public static boolean isusernameBoxEnabled = isWebElementEnabled(unameBox);
public static boolean ispWordBoxEnabled = isWebElementEnabled(pwordBox);
public static boolean issubmitBtnEnabled = isWebElementEnabled(submitBtn);
public static boolean isctrsDrpdwnEnabled = isWebElementEnabled(multyCts);
When I test it in the Test class, it always returns false. I tried diff ways of testing for existence, but it only returns false.
#Test(priority=1)
public void verifyLoginpagecontrols() {
Assert.assertTrue(isusernameBoxEnabled);
Assert.assertTrue(ispWordBoxEnabled);
Assert.assertTrue(issubmitBtnEnabled);
Assert.assertTrue(isctrsDrpdwnEnabled);
}
i found a solution that works cool with Ff and Chromre driver nevertheless fails in Htmlunit driver.
Solution for the above problem -
// Initialize the home page elements and then check for assertions;
homePagePO searchPage = PageFactory.initElements(driver,
homePagePO.class);
Assert.assertTrue(chkForThisElement(searchPage.AccManagerHref));
Assert.assertTrue(chkForThisElement(searchPage.disHref));
Sorry to say but I find several things wrong with your code :-
You have not initialized the page factory. That is the reason why you are getting the null error.
In your comment, you have said that you are finding elements by using #findBy. But why have you decalared the WebElement as static?.
Why have you declared isusernameBoxEnabled and related boolean variables as global variables. You could use the isWebElementEnabled() function in your assert directly.
Basically your isWebElementEnabled() is not useful at all if you are using page factory.
Because the moment you use unameBox, selenium looks for the element in the webpage and if not found returns a noSuchElement Exception. So unameBox wont reach isWebElementEnabled() if it is not found in the webpage.
You said there is a base class and Test class. But I don't understand how your code works if there are different classes because you have not made a reference to static variable as Assert.assertTrue(baseClass.isusernameBoxEnabled). So I am assuming that you have only one class and different methods.
Try the following code :-
public class Base {
#FindBy()
WebElement unameBox;
#FindBy()
WebElement pwordBox;
#FindBy()
WebElement submitBtn;
#FindBy()
WebElement multyCts;
}
public class Test {
#Test(priority=1)
public void verifyLoginpagecontrols() {
//initialize page factory
Base base = PageFactory.initElements(driver, Base.class);
Assert.assertTrue(base.unameBox.isEnabled());
Assert.assertTrue(base.pwordBox.isEnabled());
Assert.assertTrue(base.submitBtn.isEnabled());
Assert.assertTrue(base.multyCts.isEnabled());
}
}
Hope this helps you.

Resources