DEV Community


Posted on • Updated on

Adding automated tests to rost_gen

This week, I added some automated testing to my static site generator project, rost_gen. As the project is built using rust, it was quite easy to get started as I did not need to use any additional frameworks.

All of the code for my project is currently contained within one file. It would be better to eventually split this up into multiple files for better organization. However, it allowed me to set up a test module at the end of the file and write all of my tests in there:

mod tests {
Enter fullscreen mode Exit fullscreen mode

From there, I added functions to test different parts of my project. For example, the following tests a function that checks that a txt file is a supported file type for conversion:

fn converts_txt_files() {
  let input_file_path = path::Path::new("sample.txt");
Enter fullscreen mode Exit fullscreen mode

The function returns true or false depending on if the extension of a file is supported.

Eventually, I had to test reading of input file and generation of the html file. To do this, I would need to create test files for input and output for this scenario. However, this could cause problems unless I named all the test files differently as tests usually run in parallel. So, I decided to use the tempfile crate to create a temporary test directory for each test (where needed):

let temp_dir = tempfile::tempdir().unwrap();
let test_input_path = temp_dir.path().join("parse_title_test.txt");
Enter fullscreen mode Exit fullscreen mode

This ensures that a different test directory is used for each test and also makes the post-test clean up easier.

While writing tests, I also discovered a bug in my function for parsing link markdown into <a> tags. The function would only convert a maximum of one link per line. Quite an obvious issue but I had not considered it when I implemented this feature. So, I created an issue for this to address it in the future.

I have written tests for ruby on rails projects before. During that, and while writing tests for my rust project, I have found that tests help discover bugs that are not obvious otherwise. Thus, I believe it can be better to write tests before changing existing code or adding new features whenever possible.

Oldest comments (0)