Email Subscription Form

Saturday, February 29, 2020

More Fun With Cypress

Two weeks ago, I wrote about my first experiences using Cypress.io.  I was intrigued by the fact that it was possible to do http requests using Cypress commands, so this week I decided to see if I could combine API commands with UI commands in the same test.  To be honest, it wasn't as easy as I thought it would be, but I did manage to come up with a small proof-of-concept.


Part of the difficulty here may lie in the fact that there aren't many websites around on which to practice both UI and API automation.  For my experimentation, I decided to use the OWASP Juice Shop, which is a great site for practicing security testing.  I wanted to log into the site using an HTTP command, and then use the token I retrieved from my login to navigate to the site as an authenticated user.

Setting up the HTTP command was pretty easy.  Here's what it looks like:

var token;

describe('I can log in as a user', () => {
    it('Logs in', () => {
        cy.request({
  method: 'POST',
  url: 'https://juice-shop.herokuapp.com/rest/user/login',
  headers: {'content-type':'application/json'},
  body: {
    email: 'foo5@bar.com',
    password: '123456'
  }
})
  .then((resp) => {
    const result = JSON.parse(JSON.stringify(resp.body));
    token = result.authentication.token;
        expect(resp.status).to.eq(200);
    })
});
});

Let's take a look at what's happening here.  First I declare the token variable.  The 'I can log in as a user' and 'Logs in' parts are just the names of the test section and the test.  Then we have the cy.request section.  This is where the http request happens.  You can see the method, the url, the headers, and the body of the request.  Next, there's the then((resp), which shows what the test is doing with the response.  With const result = JSON.parse(JSON.stringify(resp.body)), I'm parsing the body of the response into JSON format and saving it to a result variable.  Then I'm setting the token variable to result.authentication.token.  Finally, with expect(resp.status).to.eq(200) I'm doing a quick assertion that the status code of the response is 200 just to alert me if something didn't come back correctly.

Next, I loaded the web page, and included the token in the browser's local storage so the web page would know I was authenticated:

describe('Is logged in', function() {
  it('Is logged in', function() {
    cy.visit('https://juice-shop.herokuapp.com/#/', {
    onBeforeLoad (win) {
      win.localStorage.setItem('token', token)
    },
  })
    cy.contains('Dismiss').click();
    cy.contains('Your Basket').should('be.visible');
  })
});

With this line: cy.visit('https://juice-shop.herokuapp.com/#/' I'm navigating to the web page.  With the next section:

    onBeforeLoad (win) {
      win.localStorage.setItem('token', token)
    },
  })

I'm telling the browser to put the token I saved into local storage.  There was a popup window with a "Dismiss" button that appeared in the browser, so I closed it with cy.contains('Dismiss').click(). And finally with cy.contains('Your Basket').should('be.visible') I asserted that the link called "Your Basket" was visible, because that link doesn't appear unless the user is authenticated.

My code definitely wasn't perfect, because I noticed that when I manually logged in, I saw my email address in the Account dropdown, but when I logged in through Cypress, the email address was blank.  I also tried doing some other UI tasks, like adding an item to my cart, but I had trouble simply because the application didn't have good element identifiers.  (I so appreciate developers who put identifying tags on their elements!  If your developers do this, please thank them often.)  And there may be irregularities with this application because it was specifically designed to have security holes.

It would be very interesting to see how easy it would be to set up API and UI testing in Cypress when testing an application with normal authentication processes and good element identifiers!  However, I think my experiment showed that it's fairly easy to integrate API and UI tests together in Cypress.

Saturday, February 22, 2020

Book Review: The Unicorn Project

As I mentioned in a previous post, it's my goal this year to read and review one tech-related book each month.  This month, I read The Unicorn Project, by Gene Kim.  The book is a work of fiction, and is the story of an auto parts supply company that is struggling to participate in the digital transformation of retail business.  I was a bit dubious about reading a work of fiction that aimed to tackle the common problems of DevOps; I assumed either the lessons or the story would be boring.  I'm happy to say that wasn't the case!  I really enjoyed this tale and learned a lot in the process of reading it. 



The hero of the story, Maxine, goes through the same trials and tribulations that we all do in the workplace.  At the beginning of the book, Maxine has just been chosen to be the "fall guy" for a workplace failure, even though she had nothing to do with it and was actually on vacation at the time.  As a punishment, she is sent to a project that is critical for the company's success, but has been bogged down for years in a quagmire of environments, permissions, and archaic processes. 

I could definitely relate to Maxine's frustrations.  One day I was having a particularly tough day at work, and I was reading the book on my lunch break.  Maxine had been working for days to try to get a build running on her machine, and she had opened a ticket to get the appropriate login permissions.  She sees that there's been progress on the ticket, but when she goes to look at it, it's been closed because she didn't have the appropriate approval from her manager.  So she opens a new ticket and gets her manager's approval, only to have the ticket closed because the manager's approval wasn't allowed to be in the "Notes" field!  My troubles that day were different, but I too had been struggling with getting the build I needed; I felt like shouting into the book: "Honey, I feel your pain!"

The real magic in the story comes when a small band of people from various departments gathers together to try to make some huge process changes in the company.  They are aided by a surprise mentor, who tells them about the Five Ideals of the tech workplace:

1. Locality and Simplicity- having locality in our systems and simplicity in our processes
2. Focus, Flow, and Joy- people can focus on their work, flow through processes easily, and experience the joy of understanding their contributions
3. Improvement of Daily Work- continually improving processes so that day-to-day operations are simple
4. Psychological Safety- people feel comfortable suggesting changes, and the whole team owns successes and failures without playing the blame game
5. Customer Focus- everything is looked at from the lens of whether it matters to the customers

Using those Five Ideals, Maxine and her fellow rebels are able to start making changes to the systems at their company, sometimes with permission and sometimes without.  I don't want to give away the ending, but I will say that the changes they make have a positive impact.

There were a couple of key things I learned from this book, which have given me a new understanding of just how important DevOps is.  The first is that when we create a new feature or verify that an important bug has been fixed, it means nothing until it's actually in the hands of customers in Production.  I have fallen for the fantasy of thinking that something is "Done" when I see it working correctly in my test environment, but it's important to remember that to the customer, it is totally not done!

The second thing I learned is the importance of chaos testing.  As companies move further toward using microservices models and cloud technologies, we need to make sure we know exactly what will happen if one of those services or cloud providers is unavailable.  Chaos testing is a great way to simulate those failures and help teams create ways to fail more elegantly; for example, by having a failover system, using cached data, or including a helpful error message.

I'll be thinking about this book for a long time as I look at the systems I work with.  I definitely recommend this book for developers, testers, managers, and DevOps engineers!

Saturday, February 15, 2020

Why I'll Be Using Cypress For UI Automation

I've mentioned in previous posts that I don't do much UI automation.  This is because the team projects I am currently on have almost no UI, and it's also because I'm a strong believer that we should automate as much as we can at the API level.  But I had an experience recently that got me excited about UI testing again!

I was working on a side project, and I needed to do a little UI automation to test it out.  I knew I didn't want to use Selenium Webdriver, because every time I go to use Webdriver I have so much trouble getting a project going.  Here's a perfect example: just one year ago, I wrote a tutorial, complete with its own GitHub repo, designed to help people get up and running with Webdriver really quickly.  And it doesn't work any more.  When I try to run it, I get an error message about having the wrong version of Chrome.  And that is why I hate Webdriver: it always seems like I have to resolve driver and browser mismatches whenever I want to do anything.



So instead of fighting with Webdriver, I decided to try Cypress.  I had heard good things about it from people at my company, so I thought I'd try it for myself.  First I went to the installation page.  I followed the directions to install Cypress with npm, and in a matter of seconds it was installed.  Then I started Cypress with the npx cypress open command, and not only did it start right up, I also got a welcome screen that told me that there were a whole bunch of example tests installed that I could try out!  And it automatically detected what my browser was, and set the tests to run on that version!  When I clicked on the Run All Tests button, it started running through all the example tests.  Amazing!  In less than five minutes, I had automated tests running.  No more Chrome version must be between 71 and 75 messages for me!

The difference between Cypress and Webdriver is that Cypress runs directly in the browser, as opposed to communicating with the browser.  So there is never a browser-driver mismatch; if you want to run your tests in Firefox, just type npx cypress run --browser firefox, and it will open up Firefox and start running the tests.  It's that easy!  In comparison, think about the last time you set up a new Webdriver project, and how long it took to find the Firefox driver you needed, install it in the right place, make sure you had the PATH configured, and reference it in your test script.

Here are some other great features of Cypress:

  • There's a great tutorial that walks you through how to write simple tests.
  • Every test step has a screenshot associated with it, so you can scroll back in time to see what the browser looked like at each step.
  • Whenever you make a change to your test and save, the test automatically runs in the browser.  You don't need to go back to the command line and rerun a command.
  • You don't have to act like a user.  For example, you can make a simple HTTP request to get an authentication token instead of automating the typing of the username and password in the login fields.  
  • You can stub out methods.  If you wanted to test what happens when a certain request returned an error, you can create a stub method that always returns an error and call that instead of the real method.
  • You can mock HTTP requests.  You can set an HTTP request to return a 404 and see what that response looks like.
  • You can spy on a function to see how many times it was called and what values it was called with.
  • You can manipulate time using the Clock method- for example, you can set it to simulate that a long period of time has elapsed in order to test things like authentication timeouts.
  • You can run tests in parallel (although not on the same browser), and you can run tests in a Continuous Integration environment.

In addition, the Cypress documentation is so clear!  As I was investigating Cypress, it was so easy to find what I was looking for.  

If you are tired of fighting with Webdriver and are looking for an alternative, I highly recommend that you try Cypress.  In less than ten minutes, you can have a simple automated test up and running, and that's a small investment of time that can reap big rewards!


Saturday, February 8, 2020

"Less" is More Part II: Headless Browser Testing

Last week we talked about serverless architecture, and we learned that it's not really serverless at all!  This week we're going to be learning about a different type of "less": headless browser testing.

Headless browser testing means testing the UI of an application without actually opening up the browser.  The program uses the HMTL and CSS files of the app to determine exactly what is on the page without rendering it.

Why would you want to test your application headlessly?  Because without waiting for a webpage to load, your tests will be faster and less flaky.  You might think that it's impossible to actually see the results of your testing by using the headless method, but that's not true!  Headless testing applications can use a webpage's assets to determine what the page will look like and take a screenshot.  You can also find the exact coordinates of elements on the page.

Something important to note is that headless browser testing is not browserless testing.  When you run a headless test, you are actually running it in a specific browser; it's just that the browser isn't rendering.  Chrome, Firefox, and other browsers have added code that makes it possible to run the browser headlessly.  


To investigate headless browser testing, I tried out three different applications: Cypress, Puppeteer, and TestCafe.  All three applications can run in either regular browser mode or headless mode, although Puppeteer is set to be headless by default.  I found great tutorials for all three, and I was able to run a simple headless test with each very quickly.  

Cypress is a really great UI testing tool that you can get up and running in literally minutes.  (I'm so excited about this tool that it will be the subject of next week's blog post!)  You can follow their excellent documentation to get started:  https://docs.cypress.io/guides/getting-started/installing-cypress.html.  Once you have a test up and running, you can try running it headlessly in Chrome by using this command:  cypress run --headless --browser chrome.

Puppeteer is a node.js library that works specifically with Chrome.  To learn how to install and run it, I used this awesome tutorial by Nick Chikovani.  I simply installed Puppeteer with npm and tried out his first test example.  It was so fun to see how easy it is to take a screenshot headlessly!

Finally, I tried out TestCafe.  To install, I simply ran npm install -g testcafe.  Then I created a basic test file with the instructions on this page.  To run my test headlessly, I used this command: testcafe "chrome:headless" test1.js.

With only three basic tests, I barely scratched the surface of what these applications can do.  But I was happy to learn just how easy it is to set up and start working with headless browser tests.  I hope you find this helpful as you explore running your UI tests headlessly.  

Saturday, February 1, 2020

"Less" is More, Part I: Serverless Architecture

Have you heard of serverless architecture and wondered what it could possibly be?  How could an application be deployed without a server?  Here's the secret: it can't.

Remember a few years ago when cloud computing first came to the public, and it was common to say "There is no cloud, it's someone else's computer"?  Now we can say, "There is no serverless; you're just using someone else's server".

Serverless architecture means using a cloud provider for the server.  Often the same cloud provider will also supply the database, an authentication service, and an API gateway.  Examples of serverless architecture providers include AWS (Amazon Web Services), Microsoft Azure, Google Cloud, and IBM Cloud Functions.



Why would a software team want to use serverless architecture?  Here are several reasons:

  • You don't have to reinvent the wheel.  When you sign up to use serverless architecture, you get many features such as an authentication service, a backend database, and monitoring and logging directly in the service.  
  • You don't have to purchase and maintain your own equipment.  When your company owns its own servers, it's responsible for making sure they are safely installed in a cool place.  The IT team needs to make sure that all the servers are running efficiently and that they're not running out of disk space.  But when you are using a cloud provider's servers, that responsibility falls to the provider.  There's less initial expense for you to get started, and less for you to worry about.  
  • The application can scale up and down as needed.  Most serverless providers automatically scale the number of servers your app is running on depending on how much demand there is for your app at that moment.  So if you have an e-commerce app and you are having a big sale, the provider will add more servers to your application for as long as they're needed, then scale back down when the demand wanes.
  • With many serverless providers, you only pay for what you use.  So if you are a startup and have only a few users, you'll only be paying pennies a month.  
  • Applications are really easy to deploy with serverless providers.  They take care of most of the work for you.  And because the companies that are offering cloud services are competing with each other, it's in their best interest to make their development and deployment processes as simple as possible.  So deployments will certainly get even easier in the future.  
  • Monitoring is usually provided automatically.  It's easy to take a look at the calls to the application and gather data about its performance, and it's easy to set up alarms that will notify you when something's wrong.

Of course, nothing in life is perfect, and serverless architecture is no exception.  Here are some drawbacks to using a serverless provider:

  • There may be some things you want to do with your application that your provider won't let you do.  If you set up everything in-house, you'll have more freedom.
  • If your cloud provider goes down, taking your app with it, you are completely helpless to fix it.  Recently AWS was the victim of a DDoS attack.  In an effort to fight off the attack, AWS blocked traffic from many IP addresses.  Unfortunately some of those addresses belonged to legitimate customers, so the IP blocking rendered their applications unusable.  
  • Your application might be affected by other customers.  For example, a company that encodes video files for streaming received a massive upload of videos from one new customer.  It swamped the encoding company, which meant that other customers had to wait hours for their videos to be processed.  

How do you test serverless architecture?  The simplest answer is that you can test it the same way you would test an in-house application!  You'll be able to access your web app through your URL in the usual way.  If your application has an API, you can make calls to the API using Postman or curl or your favorite API testing tool.  

If you are given login access to the serverless provider, you can also do things like query the datastore, see how the API gateway is set up, and look at the logs.  You'll probably have more insight into how your application works than you do with a traditionally hosted application.  

The best way to learn how serverless architecture works is to play around with it yourself!  You can sign up for a free AWS account, and do this fun tutorial.  The tutorial takes only two hours to complete, and in it you see how to create a web application with an authentication service, an API gateway and a back-end data store.  It's a little bit out of date, so there are some steps where the links or buttons are a bit off from the instructions, but it's not too hard to figure out.  When you get to the end, check out this Stack Overflow article to correct any authentication errors.  

After you get some experience with serverless architecture, you will have no trouble figuring out all kinds of great ways to test it.  Next week, I'll talk about another important "Less".  Be sure to watch for my next post to find out what it is!

New Blog Location!

I've moved!  I've really enjoyed using Blogger for my blog, but it didn't integrate with my website in the way I wanted.  So I&#...