tl;dr
Is it possible to change the LANGUAGE
environment setting (or the LC_MESSAGES
component of the locale) platform-independently, and if not (which is probably the case) to detect whether the value requested was in fact legal/took effect?
Context
One of my functions tried to detect the occurrence of a particular error by grep()
ing the text of the error message. As previously pointed on an R mailing list (can't find the reference right now), this approach is fragile: the text of the message can change based on the setting of the LANGUAGE
environment variable.
So I'm changing my code to not do that, but I'd like to add a regression test to the package that tests whether the problem occurs. And I'd like it to work (or at least not fail) across platforms.
As described e.g. in this question, I can use Sys.setenv(LANGUAGE=...)
or Sys.setlocale("LC_MESSAGES",.)
to change the message language. But this will only work if I guess the right LANGUAGE
/LC_MESSAGES
value, and it's available on the current system. (It seems that LANGUAGE
is a language code, and LC_MESSAGES
is a locale, and that the locale need not be installed if I just want to switch languages?)
Sys.getenv("LANGUAGE") ## [1] "en_CA:en"
test_msg <- function(msg,silent=FALSE) {
grepl(msg,try(x ,silent=silent))
}
test_msg("not found") ## TRUE ("object 'x' not found")
Sys.setenv(LANGUAGE="fr")
test_msg("introuvable")
## Erreur : objet 'x' introuvable
So far, so good. But resetting the LANGUAGE
variable doesn't seem to work ...
Sys.setenv(LANGUAGE="en")
Sys.getenv("LANGUAGE")=="en" ## TRUE
test_msg("not found") ## FALSE ('introuvable')
Sys.setenv(LANGUAGE="en_CA:en")
test_msg("not found") ## FALSE ('introuvable')
Setting LC_MESSAGES
to C seems more reliable ...
Sys.setlocale("LC_MESSAGES", "C")
test_msg("not found")
FWIW I've found that this sequence of commands actually seems to be unreliable, i.e. the same attempt to set the environment variable seems to work sometimes depending on what pissing around I've done previously ... I have to go back and keep starting with a clean session to get reproducible results ...
In any case, I know that if I were to try this on a computer without a French locale available, or where the locale/language name was different, that it wouldn't work. I'd like to be able to figure out whether the language setting has worked. I can use test_msg("introuvable")
as brute force, but I'm hoping there's a more elegant option ...
relevant bits of sessionInfo()
:
R Under development (unstable) (2018-11-26 r75681)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.5 LTS
locale:
[1] LC_CTYPE=en_CA.UTF8 LC_NUMERIC=C
[3] LC_TIME=en_CA.UTF8 LC_COLLATE=en_CA.UTF8
[5] LC_MONETARY=en_CA.UTF8 LC_MESSAGES=en_CA.UTF8