samedi 7 décembre 2019

How should I handle testing of a Go function that uses runtime.GOOS?

I'm writing a Go package that needs to interact with the Linux command line. Since the CLI tools that my code is interacting with are Linux specific, I first need to make sure that the OS is Linux, and then I can check for the presence of the CLI tools. My function to test the OS is as follows:

func isLinux() bool {
    return runtime.GOOS == "linux"
}

Realistically, the statement within the function can only return a boolean value. The result of the boolean being true or false seems to be wholly dependent on the testing environment too - so unless I run the tests across different OSes, I have to just assume that the function would return false in a Windows environment.

Is there a way for me to temporarily set the value of runtime.GOOS for the purpose of testing?

Would passing runtime.GOOS to the function as a string parameter be worthwhile? It would allow me to test the function more easily (because I could pass in string literals for different OSes), but since the function is so specific, and the snippet is so small, I'm not sure whether parameterising it would be worthwhile.

EDIT: It's more of a hypothetical question, I'm not really sure whether it's even worth testing given the size of the function. But, when I write code that's reliant on the current OS, how should I write it to facilitate testing - should I always to take the OS as a parameter so that I can easily mock it, or is there a way for me to temporarily override the value of runtime.GOOS?

Aucun commentaire:

Enregistrer un commentaire