TypedDevs / bashunit

A simple testing library for bash scripts. Test your bash scripts in the fastest and simplest way, discover the most modern bash testing library.
https://bashunit.typeddevs.com
MIT License
316 stars 27 forks source link

Example on how to test a function #233

Closed pmusset closed 10 months ago

pmusset commented 10 months ago

In the examples here, I think it misses one that shows how to test a specific function in a script.

For example, in a directory organised like that, as describe in your quickstart guide,

.
├── lib
│   └── bashunit
├── example.sh
└── tests
    └── example_test.sh

I am not sure what I have to write in example_test.sh to test a function in example.sh. Should I source example.sh ? But according to your own tests (for example here) it doesn't seem to be the case.

antonio-gg-dev commented 10 months ago

Hello @pmusset ! First of all, thank you very much for using bashunit!

You are correct, you should add source example.sh at the beginning of your example_test.sh, personally, I recommend you do it within the set_up function.

function set_up() {
  source example.sh
}

This way, all the functions within the file will be loaded from scratch before each test inside that file is executed.

In the example you mentioned, we are not using source because bashunit uses itself for testing, so it doesn't need to import its own functions as they have already been imported previously in the runtime.

But the standard is to have to do it.

I hope I have resolved your doubts and if you have any other questions do not hesitate to let us know.

antonio-gg-dev commented 10 months ago

I also wanted to thank you for giving us feedback on the example @pmusset . You are absolutely right. I will add it as soon as possible, but if you want, you can do it yourself and make us a PR, we would really appreciate it a lot.

Chemaclass commented 10 months ago

Thanks for your feedback, @pmusset. I created this PR to split the example into two: one to test bash functions and another to test an executable bash script. Does this helps?

pmusset commented 10 months ago

Thanks to both of you. Now I understand better.

So that also means that the file that is sourced shouldn't contain any code that will execute when it is sourced, right ?

Chemaclass commented 10 months ago

@pmusset, that would depend on the way you are designing your logic. There is no right or wrong here, and for either way, you can have tests for it.

My personal preference: 1) I prefer to have isolated functions and test them from an isolated perspective for small/unit tests. 2) And then, also some more generic tests which need to be "sourcing" the whole file as that's how you execute a bash script in the end.

Chemaclass commented 10 months ago

Closed as the question was answered and the example code was improved here https://github.com/TypedDevs/bashunit/pull/234