Wednesday, November 12, 2014

Testing with Perl - Test::More

The More module available via CPAN is part of the Test::* series and provides a wide range of testing functions. In the previous post we learned that TAP is just a simple text-based interface between testing modules that are part of  a test harness; Test::More is one of these modules that utilizes TAP and expands the "simpleness" of the protocol by providing various ways to say "ok". It includes, among other things:
  • Better diagnostics (not just OK / NOT OK, but also for example WHY)
  • Capability to skip tests given a range of criteria
  • Capability to test futures features (using TODO)
  • Compare complicated data structures
Lets jump right in and use the above referenced module to test a web application available at myapp.com (this is a fictitious web site that does not exist). As part of our test we should:
  1. Navigate the login page
  2. Make sure we are in the correct starting point
  3. Enter our login credentials
  4. Login to the site
  5. Verify our landing page after the login operation.
Implemented as a Perl test script that uses Selenium::Remote::Driver and Test::More we might write the above as:
1:  $driver->get($page);  
2:  my $loc1 = $driver->get_current_url();  
3:  is ( $loc1, LOGINHOME, 'Verify landing page' );  # THIS IS TEST 1
4:  login_as( $user_id, $password );  
5:  my $loc2 = $driver->get_current_url();  
6:  is ( $loc2, APPHOME, 'Verify landing page after login' );  # THIS IS TEST 2

In line 1 we navigate to our starting page (the login page) using Selenium's get method. In line 2 we declare a variable that will hold the URL we just navigated to and that will be returned by Selenium's get_current_url method. Then, in line 3, we utilize Test::More's is() is function to assert that the page we landed on, '$loc1', is in fact the expected one 'LOGINHOME'. Line 4 executes a page object who's sole purpose is to login to the web application under test. After the login operation we once again get the url of the page we landed on, '$loc2', and compare that to the page we expect to be after the login which is 'APPHOME'.

NOTE: I used the term Selenium above for readability to refer to Selenium::Remote::Driver - the Perl binding to WebDriver. 

Below is the output that would be sent to the harness in a PASS case:
 ok 1 - Verify landing page  
 ok 2 - Verify landing page after login  

And the output for a FAIL case:
 not ok 1 - Verify landing page  
 not ok 2 - Verify landing page after login  

Whenever a test fails, one of the features of Test::More is that it gives you meaningful information (the whys) you can use when evaluating test failures. For example, in the above failure the following would be sent to the error output file:
 #  Failed test 'Verify landing page'  
 #  at C:\Users\Freddy Vega\SsApp\create_decision_tree.pl line 107.  
 #        got: 'http://myapp.com/myloginpage'  
 #   expected: 'http://myapp.com/Account/Login'  
 #  Failed test 'Verify landing page after login'  
 #  at C:\Users\Freddy Vega\SsApp\create_decision_tree.pl line 113.  
 #        got: 'http://myapp.com/Apphome'  
 #   expected: 'http://myapp.com/Home'  
 # Looks like you failed 2 tests of 2.  

As you can probably see by now, testing with Perl means not to re-invent the wheel every time a testing problem arises. In our solution we were able to use Selenium::Remote::Driver to drive our application under test (a web app). We used Test::More to make our assertions while we are testing and TAP::Harness to tie it all together and produce results that can later be mined, interpreted and presented to different audience types (management, users, developers, etc).

In the next post in this series I tell you about test harnesses and how you can combine these with other tools to help you design a robust automation framework.

Monday, November 10, 2014

Testing with Perl - TAP (the Test Anything Protocol)

While there are many programming languages out there that folks seem to prefer when implementing automation for web and PC based applications (e.g. Python, Ruby), I've been inclined to choose Perl just about every time I have been asked to solve some testing problem. There are several reasons, I believe, why I have always chosen Perl over other candidates, below are my current top three:
  1. Cross platform support for your tests (write once run everywhere)
  2. Powerful text parsing
  3. No need to re-invent the wheel (there are thousands of modules available on CPAN)
TAP (or Test Anything Protocol) is a "simple text-based interface between testing modules in a test harness. TAP started life as part of the test harness for Perl"; it should be noted that, even though it was originally designed for and used in the development of Perl itself, TAP now has implementations in C, C++, Python, PHP, Perl, Java, JavaScript, and others as well. So this should tell you that at least programmers have noticed and have found the protocol helpful enough to port it to their language.

Our purpose for TAP is very simple: to say 'ok' or 'not ok' in a standard way with the aim of facilitating communication between the tests and the services used to run / support the tests. That is we use the Test Anything Protocol to report their successes or failures. We can then use other tools to aggregate the information produced by our tests and present it in a human readable form. Below is a sample TAP stream so you can get an idea of what it looks like.

  1..4  
  ok 1 - Input file opened  
  not ok 2 - First line of the input valid  
  ok 3 - Read the rest of the file  
  not ok 4 - Summarized correctly # TODO Not written yet  

The above stream output states that we ran 4 tests (1..4). Two of them passed (1,3) while two of them failed (2,4). Simple, isn't it?

So what do you need to test with Perl? You need three things:
  1. The AUT
  2. TAP producer (e.g. Test::More module)
  3. TAP consumer (e.g. TAP::Harness module)
I'll go into details on each one of these on future posts but for now just know that a TAP producer is just a module that does "automation magic" (such as Test::More) and communicates its successes and failures to a TAP consumer (such as TAP::Harness) using the test anything protocol.

There are many testing modules on CPAN that use TAP to report their successes or failures. In this blog series we will focus on Test::More. We'll also cover (briefly) the other modules in the Test::* family of modules mainly just to be aware that they are there for you if you need them. To write robust tests in Perl to verify a web application or web site, however, you'll find that Test::More is more than adequate (no pun intended).



Wednesday, October 22, 2014

#stop29119. Campaign? Or a classic example of the "We Have to Do Something" fallacy?

 There is no denying that there has been a lot of activity regarding ISO29119 since August of this year and it doesn't seem like its going to be dying down anytime soon. The standard has certainly created a rift in the training and consulting space that has aggravated a long time rivalry between two schools of thought.

Now, in order to run a successful and, more importantly, profitable business we need to be able to compete and use any tool at our disposal to reach our vision, this includes public debates and functions. One of the things we must keep in mind when talking about standards and certifications is that its a business, most folks know this already but if you don't now you do. And its a business whether you issue a certificate at the end of the training or not, by the way. Its a business with a bottom line just like Sears. Its a business that needs to fight for its existence or fall prey to its competition.

Aside from a response from Stuard Reid the WG convenor, the ISO camp has been fairly quiet throughout this debacle. This hasn't been the case for the stop campaign side, however. From them we see statements used like: "where is your skin in the game" or "if the standard is approved all testers will be forced to succumb to and abide by it". You also read some folks say "you'll be forced to produce tons of wasteful documentation" or "before your every move you'll need to get a sign off" when talking or interacting (via social media) with folks that either don't know of the petitions' existence or have decided to abstain from signing it for a variety of different reasons.

In following this debate on Twitter, LinkedIn and the web (via individual's blogs). I have noticed a pattern in the rhetoric used by the stop campaign folks which I believe its an almost perfect implementation of the "Scare Tactic"[*1] argument which inevitably leads to a "We Have to Do Something"[*2] fallacy. In other words the standard is going to be so bad that we should all unite and do something, no matter what that something is. Even if the something is just to stop the darn thing. Sounds counter productive doesn't it? Why not offer a real solution rather than a call to arms? This is the part that has me, and a lot of others, baffled a bit.

Finally, and for the record once again, I want to be clear that I am not saying that the arguments raised by James Christie based on his own experiences and knowledge is in any way shape or form invalid. I am saying, however, that the ensuing madness does appear to fall within the model of a "Scare Tactic" and "We Have to Do Something" fallacies.

I'm not advocating for just silently accepting the standard either, I'm advocating for doing your own research and coming to your own conclusions based on your own independent investigation.

Even if one believes the allegations expressed by the supporters of the stop campaign it makes you wonder why the scare tactic? As humans we are thinking creatures. We like to be presented with information and be able to analyze that information and come up with our own conclusions. But when things are framed in a way that it is meant to scare or force people into signing, it makes one wonder if there is anything more to this debate. Anything more than business profit, business market share, and of course the all important human mind share.

What say you?



[*1] Scare Tactic (Also Paranoia): A variety of Playing on Emotions, a raw appeal to fear. A corrupted argument from Pathos.(E.g., "If you don't do what I say we're all gonna die! In this moment of crisis you can't afford the luxury of thinking or trying to second-guess my decisions. Our very lives are in peril!  We need united action, now!")

[*2] We Have to Do Something: The dangerous contemporary fallacy that in moments of crisis one must do something, anything, at once, even if it is an overreaction, is totally ineffective or makes the situation worse, rather than "just sit there doing nothing." (E.g., "Banning air passengers from carrying ham sandwiches onto the plane probably does nothing to deter potential hijackers, but we have to do something to respond to this crisis!") This is a corrupted argument from pathos.

Thursday, October 16, 2014

Purpose, Mission and Vision keep testers self focused on things that matter

Purpose, Mission and Vision may sound like pointy hair  mumbo jumbo to you but what if it isn't?. In fact I believe it applies to testing and, specifically to Context Aware Testing.

To be context aware means to adapt according to the location, the collection of nearby people, and accessible resources as well as to changes to such things over time. To be a context aware tester means that you have the capabilities to examine the computing and human environments and react to changes to the environments that may affect the product under test.

To help guide us in our journey the Context Aware Tester always lays out his "Test Pact" from the onset. The pact includes the Purpose (the why), Mission (the how) and Vision (the what) for her testing. Lets review an example:

As a contractor she bids for and wins an assignment to test Widget A (an address book application for Windows). During a meeting with the stakeholders you find out this application is for internal use only, their main concern is stability and don't want the app to crash and cause loss of contact information.

From this bit of information we can begin to define our Test Pact:
  • You start with your purpose. To make sure the contacts application is stable by testing it using real world scenarios.
  • We then lay out what it is that we anticipate when we're done, our vision. This is our definition of done. In this case we anticipate application stability.
  • Next we state the mission. How are we going to accomplish our goal of verifying the state of the application stability. Load testing, stress testing, volume testing.
By defining your purpose, mission and vision before starting your testing project (no matter how small) you'd have given yourself a road map as well as a set of constraints to wrap around your testing effort to help keep you focused on the things that matter most (i.e. what's important). Once you start working, this is also a great way to gauge if what you are being asked to do now (an interruption) interferes with or contradicts any of the Test Pacts you are currently working on.

In nutshell Test Pacts encapsulate the definition of testing for its specific context in the form of purpose, vision and mission. This implies that for a context-aware tester, the definition of testing is not only depending on context, but also possibly different each time.

To a context aware tester, purpose (why) is her guide while the mission (how) is what drives her towards the vision (what). This keeps us closely and tightly aligned with, not only the technical aspects, but also the vision, of the stakeholders as captured in the Test Pacts.



Wednesday, October 15, 2014

Run a test suite using Perl

So you have a bunch of functionality you've automated and you'd like to execute the scripts unattended both on a set schedule as well as on certain triggers.
In this quick post (which I also did a while back here) I show you one way of running a test suite executing tests sequentially (i.e. one after the other) from the command line by using Perl. The script is appropriately named run_test_suite.pl
The code
1:  #!C:/Perl64/bin/perl  
2:  use strict;  
3:  use warnings;  
4:    
5:   my $result_dir = "C:\\Automation\\Tests\\$ARGV[0]\\";  
6:   opendir (my ($dh), $result_dir) or die "can't open dir: $!";  
7:    
8:   while (readdir $dh){  
9:    if ($_ =~ /pl$/){  
10:     system ( $result_dir . $_ );  
11:    }  
12:   }  
This script takes one parameter [line 5], the name of directory in the C:\Automation\Tests folder which is where the test scripts should reside. We use this value to read all of the files in the directory [line 6] and, using regular expressions, only action on the ones that end in pl [line 9] (since we're looking for Perl files). Finally we use the system function to execute the script [line 10]
Once you have the above script, assuming you have perl.exe in your path and Perl mapped to open your pl files, to run manually type
1:  c:\>run_test_suite.pl functional_tests   
Alternatively you can add the Perl script, using your services manager or crontab, to the list of services to be run periodically. Or add it to your CI flow to be executed when certain conditions are met.

Thursday, October 9, 2014

The Context Aware Tester

What is Context?
"The word "context" stems from a study of human "text"; and the idea of "situated cognition," that context changes the interpretation of text" ***

What does it means to be a Context Aware Tester?
A Context Aware tester knows (see above) that context changes the interpretation of what "testing" and "tests" means. And, as well:
  1. A context-aware tester knows that each situation will most likely require a custom approach.
  2. Likewise, A context-aware tester rejects the notion that a specific approach is the only approach to all problems.
  3. A context-aware tester does not reject any practice, technique, or method (not even another approach) when it comes to the who, what, when, where, and why of testing.


In his 1994 paper at the Workshop on Mobile Computing Systems and Applications (WMCSA), Bill Schilit introduces the concept of context-aware computing and describes it as follows:
Such context-aware software adapts according to the location of use, the collection of nearby people, hosts, and accessible devices, as well as to changes to such things over time. A system with these capabilities can examine the computing environment and react to changes to the environment.
-- Schilit et al 1994

Just like Schilit describes "context-aware software" as adapting "according to the location of use, the collection of nearby people, and accessible devices as well as to changes to such things over time.", so is a Context Aware tester and in doing so has the capabilities to examine the computing and human environment and react to changes to the environment that may affect the product under test.
Oh, and no, being a Context Aware tester does not mean you are now a member of a school. Context Aware is not a school. Is an approach to help solve hard, and easy, testing problems.



*** http://en.wikipedia.org/wiki/Context_awareness#Qualities_of_context

Monday, October 6, 2014

A method to Data Drive your Selenium automated tests

I was just approached by a colleague who wanted to know how I data drive my tests when automating. Since this is probably a common enough question I figured I share in my blog.

One of my favorite approaches to data drive my tests is to use database tables to store the data. By using a database, such as MySql, you save yourself a lot of time in the maintenance and mining of the test data. You also get to, based on the query, select only certain type of data to be included during the current test run.

Lets say for example that you want to test the login function of your web application / site. You already have a user table set up in your database that has a large amount of user names, passwords in different combinations (e.g. valid user, invalid user, male, female, etc). You can leverage MySql by constructing a query that covers the specific users you would like run the test for.

Below is a quick example to try to illustrate the above.

DB test_data_tbl:
user_id        password        gender        active
user1          user1pw           male            1
user2          user2pw           male            0
user3          user3pw           female         1

Pseudo code:
1) Query the database for all valid users that are male
2) For each of the users returned
2a) Instantiate Selenium
2b) Open the home / start page
2c) Login to the application
2d) Close the session

Sample code in Perl:
1:  my $query = "SELECT user_id, password  
2:             FROM test_data_tbl  
3:             WHERE account_active = true  
4:             AND gender = 'male'  
5:             LIMIT 3;";  
6:    
7:  while ( my( $user_id, $password ) = $sth->fetchrow_array() ) {  
8:    # SsApp is a custom module where the stuff to set up selenium has been abstracted.  
9:    my $driver = Custom::SsApp::setup_selenium( \%desired_capabilities );  
10:    $driver->get( APPHOME );  
11:    $driver->find_element( $user_name_target, $user_name_locator )->send_keys( $user_id );  
12:    $driver->find_element( $password_target, $password_locator )->send_keys( $password );  
13:    $driver->quit();  
14:  }  


With this approach you can have easy access to your test data by just querying a database table. You can also replace the while loop with a foreach loop or whatever looping construct your programming language supports. The basic idea is to iterate through your data and execute each test using each data set.

Friday, September 26, 2014

Professional Testers Manifesto?

Around the same time that the #stop29119 campaign was being organized by the Context Driven Testing school of thought, a Professional Testers Manifesto was issued by the same school via Karen Johnson's blog post titled My Thoughts on Testing Certifications.

Below is the manifesto's text in its entirety.

I, as a professional software tester, believe:
That standards compliance is no substitute for knowledge and skills, and that possessing a certificate demonstrates neither.
That companies have been convinced that only certified testers should be hired.
That organizations who use certification as a surrogate for rigorous selection processes place the quality of their testing at risk.
That organizations who make money from creating or promoting standards and certifications are biased in their thinking by the potential financial rewards of convincing organizations that only certified testers are professional testers. Those organizations may include those who sell training, consulting or other related services.
That testing benefits from diversity and not homogeneity: that testing is not a profession that can be standardized but instead needs to remain an intellectual professional activity.
That choosing not to be certified does not mean I do not take my profession seriously. It is because I take my profession seriously that I choose not to be certified.

As soon as I read the first two sentences, I knew that this manifesto did not resonate with me. As I read on it became apparent that this was a continuation of the #stop29119 campaign, extended to certifications and training. It is basically a set of sentences that concentrate on discrediting as well as bashing the current certificate programs and their bearers.

I was expecting to find, in this manifesto, a call to unity. A call to our sense of pride and professionalism that all testers, from all schools (and even the free-thinking ones that don't choose a school) can feel proud in signing. Instead what I found was yet another list of complaints against the standards and certification folks. And that, I don't subscribe to.

 Below is my reply to each point in the manifesto. My responses are in italics.

1. I as a professional software tester, believe:
A. I find this interesting. Because this can be taken many ways, depending on perspective. But my main gripe is why is the word 'professional' included here? Are there testers that are not professionals? Do I have to sign the manifesto to be considered a professional?

2. That standards compliance is no substitute for knowledge and skills, and that possessing a certificate demonstrates neither.
A. Why do I have to declare this? Is this not known my folks in our profession already? And if not, how many do  not know? The answer is that we do not know the answer. So one cannot assume that people do not know this already.

3. That companies have been convinced that only certified testers should be hired.
A. Really? I've worked at many companies that never even heard  of classes (ISBT, RST, etc) and courses let alone of a certificate. How can we assert that companies have been convinced of this?

4. That organizations who use certification as a surrogate for rigorous selection processes place the quality of their testing at risk.
 A. Again, why do we have to declare this? An argument can be made that companies that don't know any better can be biased by a certificate and probably no one can refute this. However, this does not invalidate courses that end up in certification.

5. That organizations who make money from creating or promoting standards and certifications are biased in their thinking by the potential financial rewards of convincing organizations that only certified testers are professional testers. Those organizations may include those who sell training, consulting or other related services.
A.  Of course a company that promotes standards and certifications would be biased in their telling their customers that they should hire certified testers. Just like the folks against certifications (mainly the CDT school) are biased in their telling their customers that they should hire CDT school of thought testers and not certified testers.
 
6. That testing benefits from diversity and not homogeneity: that testing is not a profession that can be standardized but instead needs to remain an intellectual professional activity.
A. This echoes the stop29119 campaign. Tell me, fellow testers, how many of you do not know that testing benefits from diversity? Even if the manifesto is aimed at non-testers (i.e. managers, hr, etc) we're talking about common sense. Any human understands this concept intuitively as well.


7. That choosing not to be certified does not mean I do not take my profession seriously. It is because I take my profession seriously that I choose not to be certified.
A. This statement implies that the folks that are certified do not take their profession seriously. Is this the message we want to convey?

I find the Professional Testers Manifesto not to be inline with my values nor with my mission as a tester. I see it as another attempt to further polarize a community of very talented testers and engineers; and this does not serve any of us in the end. Why should we have to choose a side? There are many of us that do not feel threatened by standards nor certifications. There are many of us that view these courses the manifesto is speaking of (whether they lead to a certification or not) to be valuable source of  information, skills, and knowledge. Another weapon in your arsenal of test tools. Another perspective, if you will. This manifesto that claimed to be for all testers, IMO, really should have been called the Context Driven School of Thought Professional Testers Manifesto.

I am a professional tester and for the reasons given above, I abstained from signing the Professional Testers Manifesto.

Tuesday, September 23, 2014

Regarding Course Completion Certificates

First off I'd like to point out that I, in no way shape or form, support shady practices of _any_ consulting firm or training center that sells "certifications" without "education". In other words I do not support testing houses that are just teaching to pass a test and issuing out certificates to students that want / need these certificates in order to gain employment, advance their careers or whatever it is they do with these things, and not actually providing an education.

I am for and do support continuous learning, teaching, mentoring and advancing our community in any positive way that I can.

That being said on to business: what is the difference between the two certificates you find below? Now I am not just talking about the obvious differences; that one is from the ISTQB and the other from the CDT folks. I am also aware of the syllabus differences, not talking about those either. I am more interested in what is the underlying principle behind both of these certificates? In other words the why.

First we have the ISTQB Foundations Series Certificate of Completion



Second we have the Rapid Software Testing class (from the CDT folks) Certificate of Completion



My gut tells me that these are just two pieces of paper that probably mean something just to the bearer. But, they can also probably be used by the bearer to gain access to special clubs (probably some of them even have secret hand shakes). Or to flash at an interview in order to impress your employer and gain "favorites" when it comes down to choosing the "right candidate". Heck you can even add this to your resume / CV in bold letters so that, before the interview, you can let prospective employers / interviewers know which "special club" you belong to. These are but a few of what I think are valid uses for both of these certificates; as any other certificate.

But isn't the difference in underlying principle between both of these courses that there is no difference? Are both courses not teaching (or supposed to be teaching) skills, terminology, etc that will not only improve the knowledge of testers but also benefit their employers and customers? Are  both courses not giving you access to a network of other like minded individuals that also share a common love for testing and our profession?

Your thoughts and comments are welcomed.


Sunday, September 21, 2014

Open Letter to the Testing Community (re: ISO 29119 conflict)

Although folks have been talking about ISO29119 and its possible impact on the testing community for a while now, it wasn't until this past August at CAST 2014 that the issue really took off. James Christie, one of the speakers at the conference, gave a presentation regarding his opposition to the standard. This action is what I consider the catalyst for the opposition that has followed since then. But why the opposition? And why now? These are but a couple of questions I will try to answer during this writing. 

Who are the opponents? 
The main opponents of 29119 seemed to have gathered around the newly formed ISST whose mission, as stated on their website, is to "Advocate for the adoption of context driven testing". I have not yet found any opponent to 29119 that were not a member of the Context-Driven school of testing. And if there are any, they have not been vocal as of yet. 

Why are they opposing it? 
In order to understand the opposition, one has to do a little bit of research and go back in history (not that long just a few years). I have observed that there always has been conflict and friction going on between the ISTQB and the CDT folks. And since the creators of the petition feel that there is a link between the ISTQB and ISO29119 they must oppose it. Evidence of this as well as this opposition has been brewing on many social circles including LinkedIn and Twitter just to name a few, just do a search on any of these mediums and you'll find plenty of lively debates on the subject. In all of the conversations I follow on social media and read on blog posts from the many members of the CDT the common theme is basically the same; we must oppose the standard because we cannot standardize testing. They basically just oppose it but do not offer an alternative. This leads me to believe that they are opposing it because they must! Picture here in the USA you are a member of the Republican party and they propose a bill. The Democrats will review this bill and decide they are against it and request that all members of their party vote against this bill. But wait, what about all of the members of both political parties individual opinion about this bill? Well, that doesn’t count as much as the greater goal: to advance the parties political agendas. 

Why now? 
Quite frankly the reason this petition to #stop29119 happened is because the time was right. There was a captive audience (at CAST), a presentation was given (regarding 29119 opposition), the response was observed and the opportunity taken. And the petition was born. Granted this is an over-simplified timeline, however, based on the transcripts of roundtable discussions I have read its all based on facts. 

What about us free-thinking testers that welcome input from all schools? 
I for one choose not join any particular school of thought. I am a free-thinking tester that believes that testing has always been a human function and based on context. In fact everything we do, as humans, is based on context! I also welcome any structure or process offered by an organization or individual (standard or not), why? Because if we truly believe that testing is based on context, then obviously one must keep an open mind to _ALL_ approaches, processes and methods. Further, I think that opposing a specific approach, process or method limits our ability as a tester and does not help our customer in the long run. This is why I have abstained from signing the #stop29119 petition and urge all folks in our profession to do your own research before signing. Ask yourselves how will this standard change the way I test? My answer is, if you believe testing is a human function and based on context, it will not. 

Conclusion 
As free-thinking testers it is our responsibility to take charge of the direction we want our profession to head towards. It is my view that keeping an open mind and including everyone is the only way to stop this conflict and advance our profession. Everything has its place; standardization and certification as well as no standardization or certification. As context driven testers we should know when to choose each one. All this petition to #stop29119 is doing is polarizing testing and the members of our community. This goes against my values and my mission so I choose to abstain from signing the petition.

Monday, July 21, 2014

Interact with Windows modal dialog from your Selenium scripts

While testing web applications sometimes we encounter Windows popup dialogs (modal windows) that block operation until the dialog is cleared. Below is how I solved this issue. Please note that there are other options out there (e.g. AutoIt), however, I decided against calling an external exe and opted for integrating the tried and true Win32::GuiTest module for this task; mainly because it is written in the same language as the bindings and so there is no need to call external executables as well as learning a new "language", simply call a method.

NOTE: The workhorse of this solution is the SendKeys call.

In your test script:
1:  my $win_id = 0;  
2:  my $win_title = 'Test window title';  
3:  my $win_class = 'Class name';  
4:    
5:  $driver->key_press_native( $win_id, $win_title, $win_class, 'ENTER' );  

In the Driver.pm OR in your page object:
1:  sub key_press_native {  
2:    
3:    my ( $self, $win_id, $win_title, $win_class, $keycode ) = @_;  
4:    
5:    use Win32::GuiTest qw(FindWindowLike GetWindowText SetForegroundWindow SendKeys);  
6:     
7:    $Win32::GuiTest::debug = 0; # Set to "1" to enable verbose mode  
8:    # First find the window of interest.  
9:    my @windows = FindWindowLike( $win_id, "^$win_title", "^$win_class\$" );  
10:    
11:    # Then we iterate through that list and send the "keys" to any matching window.  
12:    for (@windows) {  
13:      SetForegroundWindow($_);  
14:      SendKeys("{$keycode}");  
15:      Custom::TagSubs::wait_for(2);  
16:    }  
17:    return;  
18:  }  

As you can see from the above, the solution requires the test developer to know the pertinent details of the window we will be interacting with (i.e. window id, window title, window class) as well as the key(s) you would like to press (i.e. keycode). Luckily Win32::GuiTest comes with a tool found in Recoder\Win32GuiTest.exe which you can use to get "Window Hints" (i.e. WinClass, WinTitle, etc).
Some caveats:
  • The solution uses the SetForegroundWindow call which means that it does require the window being interacted with to be able to be brought to the foreground.
Information on Win32::GuiTest can be found here: http://search.cpan.org/~karasik/Win32-GuiTest-1.60/lib/Win32/GuiTest.pm you can also find key codes in the module documentation.

Feel free to drop a line or comment.
Creative Commons License
VGP-Miami Web and Mobile Automation Blog by Alfred Vega is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.