How to slow down the speed of execution? - selenium-webdriver

I am using selenium web-driver with testing. I want to slow down the speed of execution.
Here is the sample code:
#Parameters({ "provider_name", "branch", "address", "clientId", "website", "UserName", "Password", "Dpid" })
public void addDematAccount(String provider_name, String branch, String address, String clientId, String website,
String UserName, String Password, String Dpid) {
driver.findElement(By.xpath("//a[contains(#href, '#/app/DematAccount/Add')]")).click();
setParameter(provider_name, branch, address, clientId, website, UserName, Password, Dpid);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
I have used driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); and Thread.sleep(2000); but not helping

There is no longer any way to control the speed of each "step" in Selenium WebDriver. At one time, there was a setSpeed() method on the Options interface (in the Java bindings; other bindings had similar constructs on their appropriately-named objects), but it was deprecated long, long ago. The theory behind this is that you should not need to a priori slow down every single step of your WebDriver code. If you need to wait for something to happen in the application you're automating, you should be using an implicit or explicit wait routine.

If you want to view it, and its too fast I would think you could maybe record your test being executed and then review it ?
See here : http://www.seleniummonster.com/boost-up-your-selenium-tests-with-video-recording-capability/
And here : http://unmesh.me/2012/01/13/recording-screencast-of-selenium-tests-in-java/
Here is some examples from the above link
public void startRecording() throws Exception
{
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
this.screenRecorder = new ScreenRecorder(gc,
new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,DepthKey, 24, FrameRateKey, Rational.valueOf(15),QualityKey, 1.0f,KeyFrameIntervalKey, 15 * 60),new Format(MediaTypeKey,MediaType.VIDEO, EncodingKey, "black",FrameRateKey, Rational.valueOf(30)),null);
this.screenRecorder.start();
}
public void stopRecording() throws Exception
{
this.screenRecorder.stop();
}
The whole purpose of automated tests ( in my opinion ) is so they can be run in the background without user interaction/without being viewed. Also, if you want to do as many tests as possible in a certain about of time speed and parallized testing is essential. If you want to view your tests being executed I think the above method would be good to ensure you don't ruin the performance of Selenium and view the execution when completed, you will have full control with the video to replay etc.

If you really want to execute your program slowly or even step by step, you can try the following approaches:
execute your program in debug mode one step at a time;
refactor your code into function blocks, only execute a block of code at one time, you will not see you code being executed slowly as in time, but it becomes easier for you to associate your codes with the results.

Related

Flink integration test(s) with Testcontainers

I have a simple Apache Flink job that looks very much like this:
public final class Application {
public static void main(final String... args) throws Exception {
final var env = StreamExecutionEnvironment.getExecutionEnvironment();
final var executionConfig = env.getConfig();
final var params = ParameterTool.fromArgs(args);
executionConfig.setGlobalJobParameters(params);
executionConfig.setParallelism(params.getInt("application.parallelism"));
final var source = KafkaSource.<CustomKafkaMessage>builder()
.setBootstrapServers(params.get("application.kafka.bootstrap-servers"))
.setGroupId(config.get("application.kafka.consumer.group-id"))
// .setStartingOffsets(OffsetsInitializer.committedOffsets(OffsetResetStrategy.EARLIEST))
.setStartingOffsets(OffsetsInitializer.earliest())
.setTopics(config.getString("application.kafka.listener.topics"))
.setValueOnlyDeserializer(new MessageDeserializationSchema())
.build();
env.fromSource(source, WatermarkStrategy.noWatermarks(), "custom.kafka-source")
.uid("custom.kafka-source")
.rebalance()
.flatMap(new CustomFlatMapFunction())
.uid("custom.flatmap-function")
.filter(new CustomFilterFunction())
.uid("custom.filter-function")
.addSink(new CustomDiscardSink()) // Will be a Kafka sink in the future
.uid("custom.discard-sink");
env.execute(config.get("application.job-name"));
}
}
Problem is that I would like to provide an integration test for the entire application — sort of like an end-to-end (set of) test(s) for the entire job. I'm using Testcontainers, but I'm not really sure how to move forward with this. For instance, this is how the test looks like (for now):
#Testcontainers
final class ApplicationTest {
private static final DockerImageName DOCKER_IMAGE = DockerImageName.parse("confluentinc/cp-kafka:7.0.1");
#Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DOCKER_IMAGE);
#ClassRule // How come this work in JUnit Jupiter? :/
public static MiniClusterResource cluster;
#BeforeAll
static void init() {
KAFKA_CONTAINER.start();
// ...probably need to wait and create the topic(s) as well
final var config = new MiniClusterResourceConfiguration.Builder().setNumberSlotsPerTaskManager(2)
.setNumberTaskManagers(1)
.build();
cluster = new MiniClusterResource(config);
}
#Test
void main() throws Exception {
// new Application(); // ...what's next?
}
}
I'm not sure how to implement what's required to trigger the job as-is from that point on. Basically, I would like to execute what was defined before, without (almost) any modifications — I've seen plenty of examples that practically build the entire job again, so that's not an option.
Can somebody provide any pointers here?
MessageDeserializationSchema is unbounded, so isEndOfStream returns false. Not sure if that's an impediment.
In order to make the pipeline more testable, I suggest you create a method on your Application class that takes a source and a sink as parameters, and creates and executes the pipeline, using those connectors.
In your tests you can call that method with special sources and sinks that you use for testing. In particular, you will want to use a KafkaSource that uses .setBounded(...) in the tests so that it cleanly handles just the range of data intended for the test(s).
The solutions and tests for the Apache Flink training exercises are organized along these lines; for example, see RideCleansingSolution.java and RideCleansingIntegrationTest.java. These examples don't use kafka or test containers, but hopefully they'll still be helpful.
I would suggest you instrument your application as an opaque-box test by interacting with it through its public API. This can be done either as an out-process test (e.g. by running your application in a container as well, using Testcontainers) are as an in-process test (by creating your Application and calling its main() method).
Now in your comments you explained, that you want to check for the side-effects of interacting with your application (Kafka messages being published). To check this, connect to the KafkaContainer with your own KafkaConsumer from within the test and use a library such as Awaitiliy to wait until the messages have been received.

How to Execute (Vector) Storage.getInstance().readObject(filePath); in Java 8 Swing Package

Windows 10 Pro
Latest Simulator
Java Swing Project
I would like to execute "Vector a1 = (Vector) Storage.getInstance().readObject(filePath);"
In a Java Swing Application running on Windows 10 platform, I tried import CodenameOne.jar in Swing package, however when executing above code, get null pointer exception in Storage.getInstance()
Is there a way to execute this in Swing?
Thoughts?
Best Regards.
Thanks, I did not init the Display, however "Display.init(Object m)" requires an Object Argument and the Init method is deprecated.
Can you please provide me the codenameone Display dependencies?
And perhaps a java Swing snippet of code to initialize Display in order to execute Storage.getInstance().readObject(filePath)
Thoughts?
Best Regards
Thanks, Passing init(working directory) solved the Exception thrown.
Here is the Code snippet used to allow me to execute:
Storage.getInstance().readObject(filePath).
String filePath = incSrv.Pwd();// gets working directory
try {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Display.init(filePath);
String fileName = "A1-MMA.properties";
Vector a1 = (Vector) Storage.getInstance().readObject(filePath);
}
});
} catch (Exception e) {
}
And it does appear to work,
However I am left with a blacked out form that appears modal.
How can I avoid this or dispose it?.
FYI: What I am creating here is a work around for serializing Vector in Codenameone. I Save Vector to file using "Storage.getInstance().writeObject(Path, Vector)"
I convert the file to bytes and write it to the Swing Server VIA socket.
Using Storage.getInstance().readObject(file) on the Swing Server I have deserialize the object into the Vector from my app.
This appears to work well and is more efficient than the current method I use to deliver complex Vectors from the app to the Swing Server.
Can you please let me know if you see a red flag with this workaround?
Like The ability to Storage.getInstance().readObject(file) on the Swing Server may go away?
This method will save a lot of time in movind Vector data to and from the App/Server.
Thoughts Best Regards
Storage.getInstance().readObject(file) // (A1ServiceSrv.java:571)
Caused this Exception:
java.lang.NullPointerException
at com.codename1.io.Storage.init(Storage.java:89)
at com.codename1.io.Storage.getInstance(Storage.java:112)
at Main.A1ServiceSrv.loadVectorFromFile(A1ServiceSrv.java:571)
Regards
12/11/2021:
Thanks Shai,
I am including in my classpath CodenameOne.jar with update date of 12/11/2021 after CN1 refresh.
Getting Same null pointer exception.
Passing in Path "C:\Src1\A1-Arms\A1-Server\A1-MMA.properties" (Absolute Path)
Also Tried "A1-MMA.properties", however I don't think Codenameone knows where my home path is since we are not initializing it as we did with
Display.init("Current Working Directory where files reside");
This is the Fresh Stack Trace w/o calling Display.init (12-20-2021)
java.lang.NullPointerException at
com.codename1.ui.Display.getResourceAsStream(Display.java:3086)
at com.codename1.io.Log.print(Log.java:327)
at com.codename1.io.Log.logThrowable(Log.java:299)
at com.codename1.io.Log.e(Log.java:285)
at com.codename1.io.Storage.readObject(Storage.java:271)
at Main.A1ServiceSrv.loadVectorFromFile(A1ServiceSrv.java:596)
vector = (Vector) Storage.getInstance().readObject(filePath); // (A1ServiceSrv.java:596)
This is hopefully fixed by this commit: https://github.com/codenameone/CodenameOne/commit/72bf283bdaaefe5207bb9fd6787578e3ef61522c if not let me know with a fresh stack

Handle device features in codename one

for learning purposes, I am trying to write a simple sleep timer app. Purpose should be to have a picker, select a number of minutes and after that time, perform certain actions. Most importantly, activate flight mode and close all other applications to save the battery.
I have a custom picker and my runnable thread, which works fine:
#Override
public void run() {
while((System.currentTimeMillis() - startTime ) / 1000 < minutes){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("interrupted, go again.");
return;
}
}
System.out.println("Wait time is over, go to sleep.");
app.timeToSleep();
however, within "timeToSleep" I now want to do things like:
Device.setFlightmodeEnabled(true); or
TaskManager.killall();
How would I achieve something like that? I have not found anything so far, but maybe I have the wrong key words to look for.
Thanks and best regards
You can access some device features via API and some via native interfaces but I don't think setting a device to flightmode is technically possible without operator or Google authorization and that's only possible on Android...

Diagnosing Response Times

I don't have too much experience in diagnosing the source of longer response times, so I was curious to find out about some methods from the more experienced.
I have a simple index page of paginated records, and each time I click to load a new page, it says the response time is a little over 300ms for 25 records. The query to pull the records isn't anything complicated, and maybe 300ms isn't that long. But I'd still like to know how to find what's taking a majority of that time, because it just feels like it's taking a bit of time.
What tools or methods could I use to find out any bottlenecks? Thanks in advance.
DebugBar is a great way to get more visibility into your Laravel App's execution. It will break out all the SQL queries and provide timings.
In addition to DebugBar, adding a simple Benchmarking class is another tactic I often use. To do this, start a timer at the very beginning of your app. Here is a sample class I've used in the past (made a couple tweaks and didn't test the code below):
<?php
class Benchmark
{
public static $events = [];
public static function start()
{
static::$events = [];
static::bench('start');
}
public static function end()
{
static::bench('end');
}
public static function bench($event)
{
static::$events[$event] = static::time();
}
public static function time()
{
list($msec, $sec) = explode(" ", microtime());
return ($msec+$sec) - static::$events['start'];
}
public static function report()
{
print_r(static::$events);
}
}
Implementation would be:
Benchmark::start();
Benchmark::bench('finished big query');
Benchmark::end();
then print out the benchmark somewhere at the end of execution:
<?php Benchmark::report() ?>
Check MySQL
Most of the time the slowdown is the database.
If you find a particular query that is slowing the page load down, use the MySQL slow query log to isolate problems further and the MySQL explain command to dissect the query to make improvements.

await Task.Delay(...) freezes if there exists a System.Windows.Forms.Form instance

The following program hangs on the DoTheStuff().Wait(); line, if running as a Console application:
namespace Test
{
using System.Threading.Tasks;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
new Form();
DoTheStuff().Wait();
}
private static async Task DoTheStuff()
{
await Task.Delay(1000);
}
}
}
It works just as expected though, if you comment out the new Form(); line. (Runs for 1sec, then quits).
How can I keep the expected behaviour and still have a Form instance?
Now, some background if you are interested:
I have an application which is hosted as a windows service (as console when testing locally).
It requires to have access to the SystemEvents.TimeChanged event.
However, as per the documentation, this only works when having a windows Form (thus not in a service or console app). A workaround is presented in the linked documentation, and consists of creating a hidden form.
Unfortunately, the program now completely freezes instead, which is caused by the combination of await and having a Form instance.
So how on earth can I still have the expected async/await behaviour while accessing the SystemEvents.TimeChanged event?
Thanks to help below, here comes modified code which works without freeze:
namespace Test
{
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
new Thread(() => Application.Run(new Form())).Start();
// SynchronizationContext.SetSynchronizationContext(null);
DoTheStuff().Wait();
}
private static async Task DoTheStuff()
{
await Task.Delay(1000);
}
}
}
In my program, I need to use "SynchronizationContext.SetSynchronizationContext(null);", since the threadpool should be used for awaiting tasks. I don't think that is a good practice, since Form obviously initialized it for a reason. But running the form hidden without user input (it is a service!), and can't see any harm right now.
The documentation feels a bit incomplete, with MS not even mentioning the issue that may arise using the example 2 (await/async implicitly changes behaviour when instantiating a Form).
This is by design. Creating a new Form object get the Winforms plumbing to install a new SynchronizationContext. Something you can see in the debugger by looking at the SynchronizationContext.Current property.
That property is big deal whenever you do anything asynchronously. If it is null, the default, then using await gets code to run on threadpool threads. If it is not then the await plumbing will implement the await by calling the SynchronizationContext.Post() method. Which ensures that your code runs on the main thread.
But that doesn't work in your program because you broke the contract. You didn't call Application.Run(). Required.
The SystemEvents class will create its own hidden notification window and pumps a message loop if you don't provide one. No need to create a form. The consequence is that its events will fire on an arbitrary thread, not your main thread. So do watch out for locking requirements.
The call to Wait causes a deadlock, as I explain on my blog and in a recent MSDN article.
In your case, you could use a simple MainAsync as such:
static void Main(string[] args)
{
MainAsync().Wait();
}
static async Task MainAsync()
{
new Form();
await DoTheStuff();
}
private static async Task DoTheStuff()
{
await Task.Delay(1000);
}
However, there are a couple of problems here. First, when you create a form (even a hidden form), you are expected to run an STA event loop, e.g., Application.Run. Second, as a Win32 service, you are expected to give your main thread back to the SCM, e.g., ServiceBase.Run.
So I would recommend a solution where you create a form and run an event loop on a secondary thread.

Resources