common/util.cc: add unit test, fix bug in util::read_file (#21251)
* add test case for util
* fix bug in read_file
* gitignore test_util
* better test
* referer
* more
* more test
* REQUIRE size
* apply reviews
* only test binary
* simplify the test
* read non-permission
* debug print
* remove /etc/shadow
* test read directory
* Update selfdrive/common/tests/test_util.cc
Co-authored-by: Adeeb Shihadeh <adeebshihadeh@gmail.com>
Co-authored-by: Willem Melching <willem.melching@gmail.com>
old-commit-hash: a873a23e0d
commatwo_master
parent
d8ac1df789
commit
6bfc7f4ca5
5 changed files with 56 additions and 2 deletions
@ -0,0 +1 @@ |
||||
test_util |
@ -0,0 +1,49 @@ |
||||
|
||||
#include <dirent.h> |
||||
#include <sys/types.h> |
||||
|
||||
#include <algorithm> |
||||
#include <climits> |
||||
#include <random> |
||||
#include <string> |
||||
|
||||
#define CATCH_CONFIG_MAIN |
||||
#include "catch2/catch.hpp" |
||||
#include "selfdrive/common/util.h" |
||||
|
||||
std::string random_bytes(int size) { |
||||
std::random_device rd; |
||||
std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char> rbe(rd()); |
||||
std::string bytes(size+1, '\0'); |
||||
std::generate(bytes.begin(), bytes.end(), std::ref(rbe)); |
||||
return bytes; |
||||
} |
||||
|
||||
TEST_CASE("util::read_file") { |
||||
SECTION("read /proc") { |
||||
std::string ret = util::read_file("/proc/self/cmdline"); |
||||
REQUIRE(ret.find("test_util") != std::string::npos); |
||||
} |
||||
SECTION("read file") { |
||||
char filename[] = "/tmp/test_read_XXXXXX"; |
||||
int fd = mkstemp(filename); |
||||
|
||||
REQUIRE(util::read_file(filename).empty()); |
||||
|
||||
std::string content = random_bytes(64 * 1024); |
||||
write(fd, content.c_str(), content.size()); |
||||
std::string ret = util::read_file(filename); |
||||
REQUIRE(ret == content); |
||||
close(fd); |
||||
} |
||||
SECTION("read directory") { |
||||
REQUIRE(util::read_file(".").empty()); |
||||
} |
||||
SECTION("read non-existent file") { |
||||
std::string ret = util::read_file("does_not_exist"); |
||||
REQUIRE(ret.empty()); |
||||
} |
||||
SECTION("read non-permission") { |
||||
REQUIRE(util::read_file("/proc/kmsg").empty()); |
||||
} |
||||
} |
Loading…
Reference in new issue