简体   繁体   中英

Writing proper unit tests

I am brand new to creating unit tests, and attempting to create tests for a project I did not create. The app I'm working with uses python/flask as a web container and loads various data stored from js files into the UI. I'm using pytest to run my tests, and I've created a few very simple tests so far, but I'm not sure if what I'm doing is even relevant.

Basically I've created something extremely simple to check if the needed files are available for the app to run properly. I have some functions put together that look for critical files, below are 2 examples:

import pytest
import requests as req

def test_check_jsitems
    url = 'https://private_app_url/DB-exports_check_file.js'
    r = req.get(url)
    print(r.status_code)
    assert r.status_code == req.codes.ok    

def test_analysis_html
    url = 'https://private_app_url/example_page.html'
    r = req.get(url)
    print(r.status_code)
    assert r.status_code == req.codes.ok

My tests do work - if I remove one of the files and the page doesn't load properly - my basic tests will show what file is missing. Does it matter that the app must be running for the tests to execute properly? This is my first attempt at unit testing, so kindly cut me some slack

While testing is such a big topic, and does not fit in a single answer here, a couple of thoughts.

It's great that you started testing. These tests at least show that some part of your application is working.

While it is ok, that your tests require a running server, getting rid of that requirement, would have some advantages.

  • you don't need to start the server:-)
  • you know how to run your tests, even in a year from now (it's just pytest )
  • your colleagues can run the tests more easily
  • you could run your test in CI (continuous integration)
  • they are probably faster

You could check out the official Flask documentation on how to run tests without a running server.

Currently, you only test whether your files are available - that is a good start.

What about testing, whether the files (eg the html file) have the correct content?

If it is a form, whether you can submit it?

Think about how the app is used - which problems does it solve?

And then try to test these requirements.

If you are into learning more about testing, I'd recommend the testandcode.com podcast by Brian Okken - especially the first episodes teach a lot about testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM