1test_that("source_file always uses UTF-8 encoding", { 2 has_locale <- function(l) { 3 has <- TRUE 4 tryCatch( 5 withr::with_locale(c(LC_CTYPE = l), "foobar"), 6 warning = function(w) has <<- FALSE, 7 error = function(e) has <<- FALSE 8 ) 9 has 10 } 11 12 ## Some text in UTF-8 13 tmp <- tempfile() 14 on.exit(unlink(tmp), add = TRUE) 15 utf8 <- as.raw(c( 16 0xc3, 0xa1, 0x72, 0x76, 0xc3, 0xad, 0x7a, 0x74, 0xc5, 0xb1, 0x72, 0xc5, 17 0x91, 0x20, 0x74, 0xc3, 0xbc, 0x6b, 0xc3, 0xb6, 0x72, 0x66, 0xc3, 0xba, 18 0x72, 0xc3, 0xb3, 0x67, 0xc3, 0xa9, 0x70 19 )) 20 writeBin(c(charToRaw("x <- \""), utf8, charToRaw("\"\n")), tmp) 21 22 run_test <- function(locale) { 23 if (has_locale(locale)) { 24 env <- new.env() 25 withr::with_locale( 26 c(LC_CTYPE = locale), 27 source_file(tmp, env = env, wrap = FALSE) 28 ) 29 expect_equal(Encoding(env$x), "UTF-8") 30 expect_equal(charToRaw(env$x), utf8) 31 } 32 } 33 34 ## Try to read it in latin1 and UTF-8 locales 35 ## They have diffefent names on Unix and Windows 36 run_test("en_US.ISO8859-1") 37 run_test("en_US.UTF-8") 38 run_test("English_United States.1252") 39 run_test("German_Germany.1252") 40 run_test(Sys.getlocale("LC_CTYPE")) 41}) 42