mercredi 16 août 2017

go lang testing: what is the best way to synchronize tests in different packages which involve with a global variable?

I'm working on a go project, my task is writing some tests for a package. The tests need to access a global variable in a different package. This global variable might be setup/access in different packages' testing. Because by default go testing runs in parallel for different packages. Therefore, setup/access to this variable might create race conditions.

The easiest way to synchronize is to create a shared sync.Mutex which spans in the different packages. Having said that, I tried to put this sync.Mutex in the xxx_test.go of xxx.go in which the global variable is declared, unfortunately, another package was not able to access this Mutex due to scope limitation. Eventually, I figured out I have to put this sync.Mutex to a utility package which is dedicated to testing, then different packages can access this Mutex to achieve sync purpose for that global variable.

I'm new to go lang. I just felt it's awkward that I need to create a utility package to just achieve sync purpose in the testing, on the other hand, if another developer does some testing in another package, he/she probably doesn't know where to find this sync.Mutex. Is there any better way to achieve this sync purpose with an elegant solution.

Many thanks!

Aucun commentaire:

Enregistrer un commentaire