So I’ve been using Cypress for a while now to test our apps, it’s an incredible testing tool, with many features developers will feel at home with and providing incredibly fast and detailed feedback which remote-browser tools cannot compete with.
However there has been a bone of contention for some. The lack of cross-browser compatibility. For now, it will only work with Chrome and Electron.
Yep, no IE10/11, Firefox, Safari, Opera etc.
Best not delete your favourite Selenium based tool just yet.
However there is some light on the horizon, and from the likes of Microsoft no less.
Rumours floated around late last year that Microsoft were ditching efforts on their budding IE11 replacement Edge, with well, Edge. Just based on Chromium this time. You can get it for Windows 10 here from Windows Insiders.
If you visit the above page on a MacOS, you’ll see a button asking you to be notified, however Twitter user WalkingCat posted up links from Microsoft’s CDN.
Thats all folks, thanks for reading, and feel free to follow me @ https://github.com/YOU54F for more of my fumblings in code.
Update :- I’ve now followed up this with another blog post where I have published a beta version of Cypress with Edge support for testing purposes. See here for the blog post with a link to an example GitHub repo and installation instructions!
The cool guys and girls over at Dius offer a dockerised implementation of the Pact-Broker for free! I know, amazing, right? You can get it right now here
However out of the box, the Docker solution is not secure. There is an example SSL configuration, utilising nginx as a reverse proxy, to allow access solely via HTTPS, provided by the PACT team.
I have extended on this implementation, to ensure we are following current industry standards for a secure nginx implementation.
Additionally we will go through the process of how to generate your own self-signed certificates and register them with a Certificate Authority to give confidence to your stakeholders and site-visitors.
We will only be using open-source tooling because open-source ftw <3.
If you haven’t already read my post about using Pact & Swagger to compliment your development workflow, you can check it out here.
It is assumed that you have registered a domain name as it is a requirement to generate your signed SSL certificates.
This example will use a dockerised postgres instance, as described in the main pact_broker-docker readme, just so you can run the example end-to-end.
If you are able to use your cloud provider to sign your certificates, then you may not need to use lets-encrypt. In my example, I am using a self-managed AWS EC2 instance, which is unable to utilise AWS certificate manager, as you are unable to download the generated ceritifcates. If you are using Fargate, this is not an issue.
Copy the contents of ssl_letsencrypt to your instance and rename to pact-broker
Replace the following occurances found in the *.sh & docker-compose.yml files in pact-broker & pact-broker/lets-encrypt
domain_name – Replace with your registered domain name
email_address – Replace with your email address. It should match the registered domain
username – Replace with the name of your user (it is assumed your folder will live in /home/username/pact-broker but you can change to suit)
Rename .env.example to .env.
Get to know your environment file
The .env file contains the credentials we will pass into the docker-compose file and ultimately to the pact-broker. More options can be added as per Pact.io documentation, but will also require adding into your docker-compose.yml file.
The database variables are setup to talk to the postgres database loaded via docker-compose.
Enable SSL protocols. TLSv1 is insecure and shouldn’t be used. TLSv1.1 is weak. For compliance reasons, TLSv1 should not be used.
ssl_protocols TLSv1.2 TLSv1.3;
Only enable known strong SSL ciphers. It is a balancing act between using strong ciphers and compatability. A site scoring 100% on a cipher test, would not be compatible with all devices. The current set gives 95% on SSLLabs security test.
If you have not already generated your certificates, please do so now
Change into the lets-encrypt folder
Run docker-compose up -d. This will load up a single page application that lets-encrypt can read from, in order to verify that the domain is owned by you.
Run ./makecertsstaging.sh – This will generate sample certificates for you, in lets-encrypt/out
Run ./makecertsinfostaging.sh – This will provide information about the generated certificates for you.
If all the above steps ran ok, we can safely remove the out dir in lets-encrypt/out to remove our staged certificates.
Run ./makecerts.sh – This will generate your signed certificates for you, in lets-encrypt/out
Run ./makecertsinfolive.sh – This will provide information about the generated certificates for you.
We can now run our secure broker
Modify the docker-compose.yml file as required.
Run docker-compose up to get a running Pact Broker and a clean Postgres database
Testing your setup
curl -v http://localhost
# This will redirect to https
curl -v http://localhost/matrix
# This will redirect to https root, not matrix
curl -v https://localhost/matrix
# This will redirect to https matrix page
# Note we don't provide the flag -k (insecure) as the website is certified
curl -v http://localhost/webhooks
curl -v https://localhost/webhooks
# This will return a 418 error
Renewing your certificates
We generated certificates with LetsEncrypt, however they will expire after 3 months. We have aimed to minimised disruption by incorporating the renewal process into our configuration, so we will just need to run a script to generate them and bounce our app.
Ensure you are in the root folder, in our example the pact-broker folder
Run ./renewcerts_staging.sh – This will run a do a dry run of the renewal process, or inform you that you don’t need to generate one yet.
Run ./renewcerts.sh – This will run the renewal process and generate you new certicates and restart your docker instance
Certificates will be output to pact-broker/letsencrypt/out/etc/letsencrypt/live//
Note, the folder is the same as our old certificates, so no change to our docker-compose file. This is because this location is actually sym-linked, and the actual certificates live in the archive folder.
Replace the dockerised postgres DB with a proper instance
You will need to make some minor changes to utilise a non-dockerised Postgres instance.
Update the following environment variables in your .env file
Some simple command-line tricks borrowed from the land of devOps to help you analyse logs and gain useful insight.
I’m under attack! Or rather, my EC2 instance is. ( A virtual machine running Ubuntu, hosted in AWS )
It’s not a mega worry for me, as it is just a sandbox for testing/development of home projects. However it is the perfect opportunity for me to demonstrate some techniques you can use to extract useful information from logs.
My virtual machine has been running for around 3 three months with port 22 which is used for ssh, left accessible publicly on the internet. The logs live in /var/log
We are going to use ls to list the contents of the directory & cat to output our file contents directly to the terminal.
$ ls /var/log/secure* secure secure-20181230 secure-20190106 secure-20190307 secure-20190310
$ cat /var/log/secure*
Mar 10 03:40:27 ip-***-**-**-** sshd: Invalid user test from 126.96.36.199 port 56702 *** MY SCREEN BUFFER INSTANTLY FILLED UP WITH STUFF LIKE THAT ***
Oh crap, I thought. Naughty, naughty h4x0rs.
I knew there was alot, but not how many, so let’s count how many failed login attempts we’ve had.
cat /var/log/secure* output the content of each of the 5 files directly to the terminal (the * is a wildcard and will pattern match any files called secure with any suffix)
| this is called a pipe, it will allow you to pass the output of the command to the left of the pipe, as an input to the command to the right of the pipe.
grep -e 'Invalid user' This is a pattern matcher, it will look for every occurance of the words Invalid user and output the entire log line, so we can trim our search to only failed login attempts
wc -l this will count how many words in a document, but we are passing the -l flag which will count how many lines (a single line for each failed login attempt
$ cat /var/log/secure* Mar 10 03:40:27 ip-***-**--**-** sshd: reverse mapping checking getaddrinfo for bd3f7386.virtua.com.br [188.8.131.52] failed - POSSIBLE BREAK-IN ATTEMPT! Mar 10 03:40:27 ip-***-**--**-** sshd: Invalid user test from 184.108.40.206 port 56702 Mar 10 03:40:27 ip-***-**--**-** sshd: input_userauth_request: invalid user test [preauth] Mar 10 03:40:27 ip-***-**--**-** sshd: Received disconnect from 220.127.116.11 port 56702:11: Bye Bye [preauth] Mar 10 03:40:27 ip-***-**--**-** sshd: Disconnected from 18.104.22.168 port 56702 [preauth]
$ cat /var/log/secure* | grep -e 'Invalid user' Mar 10 03:39:35 ip-***-**--**-** sshd: Invalid user test from 22.214.171.124 port 59039 Mar 10 03:39:36 ip-***-**--**-** sshd: Invalid user admin from 126.96.36.199 port 41233 Mar 10 03:39:42 ip-***-**--**-** sshd: Invalid user ism from 188.8.131.52 port 37902 Mar 10 03:39:43 ip-***-**--**-** sshd: Invalid user admin from 184.108.40.206 port 39222 Mar 10 03:40:27 ip-***-**--**-** sshd: Invalid user test from 220.127.116.11 port 56702
Exit and then open your terminal again, and attempt to sudo and voila. sudo at your fingertip.
$ sudo touch
I’ve always liked knowing the temps of my CPU/GPU/RAM, and fan speeds stemming from overclocking/water-cooling my PC’s but mainly I wanted to quieten my fans without melting the work laptop.
It is ridiculously loud when it spins up a set of Docker containers or a VM and it just doesn’t need to be, so I use MacsFanControl to control the fan speeds, and iStats to keep an eye on some stats.
$ sudo gem install iStats
$ istats all
Total fans in system: 2 CPU temp: 43.13°C ▁▂▃▅▆▇ Battery health: Good Fan 0 speed: 3461 RPM ▁▂▃▅▆▇ Fan 1 speed: 3502 RPM ▁▂▃▅▆▇ Cycle count: 66 ▁▂▃▅▆▇ 6.6% Max cycles: 1000 Current charge: 1927 mAh ▁▂▃▅▆▇ 28% Maximum charge: 7025 mAh ▁▂▃▅▆▇ 95.8% Design capacity: 7336 mAh Battery temp: 30.8°C
Sweet, now let’s see if we can get them on the touchbar.
Apple let us modify the touchbar to a degree, but not enough to be able to add custom icons and scripts.
It is a json config file, defining each button. You can customise with a list of predefined button types listed on their homepage, but you can also write AppleScript or your own scripts and associated them with buttons.
My config is available here as a GitHub Gist and can be seen below
It was inspired by the following plugin for BetterTouchTool
iTerm2 Touchbar integration
If you don’t have iTerm, download it with HomeBrew.
$ brew cask install iterm2
You can view the iTerm2 docs for the touchbar here.
With ZSH and a nifty plugin called zsh-iterm-touchbar, we can get our git info and run our npm run scripts in project folders.
If you aren’t already using zsh, then install it with HomeBrew
Consider the following statements that you might come across as a tester on a web app project.
Must be compatible with latest browser versions
Must be compatible with mobile
Pretty vague right? There are lots of browsers, and lots of versions. My definition of latest might be different to yours. Reminds me of this gem.
A small list of of some of the top browsers, but there are plenty more.
Internet Explorer Mobile
When they say mobile, that’s a wide range to cover. They didn’t even mention latest there. There are quite a few operating systems, and a multitude of versions, by dozens of manufacturers. The stakeholder could expect their dusty old iPad 1 & Windows 8 touchscreen tablet’s to work.
Let’s see if we can help scope that requirement down a bit, to something a bit more manageable.
Know Your Audience
Some of the most popular sites for checking the worlds browser stat usage are
Both are excellent for noticing trends in usage but if you base your testing strategy for cross-browser testing on this alone, you will find that you may be targeting the wrong market.
Chrome’s market-share dominance won’t ring true in an office full of locked-down corporate boxes with Internet Explorer.
If your company doesn’t already have analytics which records site visitors, Insist that they do. It will be pivotal in ensuring your product will work, for the people who want to use it by providing tailored facts about what devices are in use for your particular product.
The challenges for web developers and testers alike
With so many browsers out there, and more importantly so many versions each supporting different feature-sets, it can be hard to keep track, and even harder to test.
We could buy a load of real devices (logistical nightmare) or test in the cloud with a device provider such as BrowserStack / SauceLabs / TestingBot (pricey).
Both of those approaches, even if we use automation, give us slow feedback. What if we could test in 800+ browsers when our developers are writing their code. It is no substitute to UI testing, but augments our dev/testing process nicely.
We can give our developers a helping hand, and help mitigate risk as testers, so we don’t have to have such a reliance of cross-browser testing via traditional methods.
Can I use it? Yes, you can!
Software defects cost money. How much money usually depends on where it is found in the software life-cycle. An ambiguous requirement that could otherwise be firmed up into a set of agreed testable criteria before any code is written, may become something entirely different from what was envisioned, when unveiled.
I said before, we aren’t going to use any browsers for our testing, and although we want to test early, we can’t test before any code is written, as the technique we are going to apply is static-analysis.
Static analysis, also called static code analysis, is a method of computer program debugging that is done by examining the code without executing the program. The process provides an understanding of the code structure, and can help to ensure that the code adheres to industry standards.
We can utilise some tools, to cross-reference our code against the compatibility databases, targeting only the browsers and versions we are interested in.
Our developer can run these locally to keep them on track, and we can add these checks to our CI pipeline, to ensure that any new code is validated against these databases.
So hopefully by now, we have compiled a list of browsers we want to support, either by analytics, or by discussion and agreement with your stakeholders.
We are going to use a tool called browserslist to define our list of browsers to our tools.
Another CLI client that does the same as the above too, I haven’t tried this yet.
So now we’ve found some issues? What can we do?
Polyfill.io – A polyfill, or polyfiller, is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will. The following website will list what polyfill’s are required for a particular feature.
Ok, so I don’t need to test on an actual browser, just mash polyfill into everything?
Not quite, trying to support every browser with lots of polyfills will leave you with a bloated web-app and no-one likes a slow site, you will have non-functional requirements to meet as well.
We haven’t performed any functional testing here on our UI, and there is no substitute to performing automated cross-browser testing of key journeys for confidence.
However you won’t need to rely on them so heavily, to keep you informed of browser compatibility and version inconsistency, so they remain lean, quick and useful rather than the painful entanglement that they can become.
Cool story bro, but wheres the code?
I have created a simple react website in typescript with some features not supported in older browsers, it incorporates the tools discussed in the article with a working example you can experiment with and build upon.
It also showcases some other UI testing tools which will be discussed in further articles.
Reading Time:- Get a cup of tea and pull up a beanbag, I’m going to say 15 minutes
API’s (Application Programming Interfaces) have been around since 2000. I remember utilising my first one back at Uni, based in Java to modify a Lego Mindstorms NXT robotics kit to run an Artificial-Neural Network.
I dropped into the world of micro-services 5 years ago, along with a team of great engineers helping to define a service blueprint that could be used as a framework for new service providers.
I took this new found knowledge onto my next employer, who were setting up a new micro-service architecture to serve a web front-end, whilst communicating to a legacy backend through an abstraction layer, which was just another API.
We employed consumer-driven contract testing but with little collaboration from dependencies, we ended with CDC tests solely maintained by consumers which only served to protect us from changes of which we had little visibility, but it works better in collaboration and offers more benefits, than hinderances.
The aim of this article is to provide you with some tools and techniques to aid and promote collaboration with your API development workflows in order to increase the quality of your product. (After all, I am a Software Tester!)
Using Swagger to document your API
I am a big advocate of using hand-crafted Swagger definitions of each service as one of the first outputs of our developement.
You are possibly in an Agile world and you want to start rapid prototyping.
Documentation is lean – Everyone has probably laughed at you when you suggest that we write the specifications for the API right off the bat rather than 100 discussions that always have little output (see next point), let’s make it cheap and easy to change so it’s not as onerous.
Getting multiple teams together is difficult and often non-productive – your team and the teams you integrate with don’t want to sit in long meetings about boring things like what data-type a field should be.
Contracts are key – If we can agree what the request/response will look like, we don’t care about the underlying implementation, as long as it honours them. It also doesn’t mean they are set in stone, as a fixed artefact. They can change as the project develops. It also makes testers happy, as we can plan for integration testing early.
So your team want’s to start writing code and the provider hasn’t come up with an API contract yet? ( They are probably in long boring data-field style meetings ).
Fine. Let’s document the API we want to see with https://editor.swagger.io/ and save the JSON or YAML version to your machine, stick it in version control and give your provider access. Swagger will provide validation and auto-completion as you type to ensure that the swagger you have written, can be developed. ( A big bonus, I can assure you! )
They are chuffed now as they have a view as to what one of their consumers’ wants, documented in a validated specification. They can make changes as necessary, and via a pull requests, collaboratively develop the specification, and ensure that everyone is in the loop. This collaboration relationship is great to build up, as it will help us immensely in testing our services can integrate together.
So now we have our API, defined in swagger. Either written by us, our provider, or collaboratively. Whichever way you’ve got it, don’t trust it. Even though the Swagger editor provides validation whilst writing it, you can save the file with errors. Now I know you won’t do that, but someone else might. Don’t worry, we got it.
npm install --global swagger-cli
swagger-cli validate /path/to/swagger.json
Hopefully this will report no errors, but if it does, it will tell you what needs resolving. If you add this into your CI process, when someone checks in a change to the specifications, you can catch it on a pull-request, ensuring that anyone working from the specification in master, has a valid copy.
Consumer Driven Contract testing with Pact
Now we have an API specification, we can start developing our application however there are a couple of things we want to consider.
What happens if our provider isn’t ready for several months – how can we integration test it?
We can use the notion of CDC testing, also known as consumer driven contract testing, although I prefer the term collaborative driven contract testing. The former almost implies the consumer has free-reign to drive their own requirements, however it requires agreements from both parties, and participation, hence collaboration.
A formal agreement between individuals or parties.
Synonyms: agreement, protocol, deal, contract
Pacts are synonymous with API design, but how often do these get broken.
We might find that after developing our consumer or provider in isolation, when we come to integrate the systems in a test environment, that expectations are not being met, resulting in systems failing to communicate.
We can use Pact and its toolset, to enable us to generate contracts (pairs of request/responses) saved as a JSON file to use for component integration testing, in complete isolation from a service dependency whilst publishing these contracts to a central broker which can be queried at a later date by when the service is available.
Using the Pact DSL, the expected request and response are registered with the mock service.
The consumer test code fires a real request to a mock provider (created by the Pact framework).
The mock provider compares the actual request with the expected request, and emits the expected response if the comparison is correct.
The consumer test code confirms that the response was correctly understood
Results published to a broker as a JSON file
Results are tagged with a branch tag for later querying
Always read the manual
In the above example, after the tests pass (step 5), we publish the results to the broker. This presents a problem, thankfully an avoidable one. We might find that the PACT contract tests have drifted from the Swagger specification. It may be that a required field is missing from the request, or the tests expected an array, but the swagger specification defined it as a string.
This tool will tell us where that drift occurs, and you can fail your CI step, correct any errors and then re-run your CI build, ensuring that you publish post successful specification validation.
This gives us a high level of confidence, that as long as our provider sticks to the swagger specification, we should be in a good position come pact validation when our provider has their first build. We will talk about their part of the PACT testing pipeline shortly.
Fake it till you make it with Pact & Swagger Tools
So I know, trying to get your developers to write more unit tests, might seem like a hard sell, but what if we could re-use those interactions we had generated in a previous test to drive our higher level component integration & UI tests.
We create a docker image containing the standalone executable and copy in the consumer-provider JSON contract, for each service we need to mock. We can then run these locally, but CI will publish these to AWS in order to perform e2e tests, whilst we await our providers first build.
So we are now using our PACT contracts, that we generated, to perform our component integration and e2e testing, with mocks. Everything is green on your dashboard. It looks great right, time to relax.
Provider validation process with PACT
The provider retrieves its clients pacts from the broker
Each request is sent to the provider, and the actual response it generates is compared with the minimal expected response described in the consumer test
Provider verification passes if each request generates a response, that contains at least, the data described in the minimal expected result
Tests passed and results published to the broker
Using the PACT broker to protect deployments
Each application version should be tagged in the broker with the name of the stage (eg. test, staging, production) as it is deployed.
This enables you to use the following very simple command to check if the application version you are about to deploy is compatible with every other application version already deployed in that environment
$ pact-broker can-i-deploy --pacticipant PACTICIPANT --version VERSION --to TAG --broker-base-url BROKER_BASE_URL
Take home points
Write your API specifications in Swagger
Store them in version control and give access to any providers/consumers for collaboration
Validate the swagger specifications are correct with swagger-cli
Write pact tests in a unit-testing framework of your choice, using one of the many different language implementations of Pact. (We use pact-js & Jest, written in TypeScript)
Run the tests during CI to generate the contract
Validate the generated pact contract against the swagger specification during CI
If it passes, publish the pact contract to the pact broker, tag it with the branch name.
If it is part of a development/staging/production additionally tag it with an identifier
Consumers can generate mock providers from the pact contract to use in integration / UI / e2e testing
Providers can read from the pact broker and test that they meet consumer expectations, as pact will mock the clients requests specified in the contracts.
All participants can use the can-i-deploy tool at CI time, to check if its compatible with other consumer/providers in a specific environment.
For a later blog post
Follow up from this blog post, with real code based examples on a Github repository you can clone, fork and play with for real.
How pact can help you avoid supporting multiple versions of API’s and deprecate features/endpoints gracefully .
Validating your developed service against your hand-crafted swagger specification that your tester won’t stop banging on about.