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>
pull/21292/head
Dean Lee 2021-06-16 17:01:13 +08:00 committed by GitHub
parent 2c6d27f482
commit a873a23e0d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 56 additions and 2 deletions

View File

@ -208,6 +208,7 @@ jobs:
$UNIT_TEST selfdrive/athena && \
$UNIT_TEST selfdrive/thermald && \
$UNIT_TEST tools/lib/tests && \
./selfdrive/common/tests/test_util && \
./selfdrive/camerad/test/ae_gray_test"
- name: Upload coverage to Codecov
run: bash <(curl -s https://codecov.io/bash) -v -F unit_tests

View File

@ -35,3 +35,6 @@ else:
_gpucommon = fxn('gpucommon', files, LIBS=_gpu_libs)
Export('_common', '_gpucommon', '_gpu_libs')
if GetOption('test'):
env.Program('tests/test_util', ['tests/test_util.cc'], LIBS=[_common])

View File

@ -0,0 +1 @@
test_util

View File

@ -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());
}
}

View File

@ -56,8 +56,8 @@ namespace util {
std::string read_file(const std::string& fn) {
std::ifstream ifs(fn, std::ios::binary | std::ios::ate);
if (ifs) {
std::ifstream::pos_type pos = ifs.tellg();
if (pos != std::ios::beg) {
int pos = ifs.tellg();
if (pos > 0) {
std::string result;
result.resize(pos);
ifs.seekg(0, std::ios::beg);