test: Add RAII utility classes for testing

- TempFile holds specific contents
 - EnvValue sets an environment variable
pull/34/head
David Drysdale 9 years ago
parent 693e566b66
commit 834c98e9d9
  1. 27
      test/ares-test.cc
  2. 35
      test/ares-test.h

@ -6,6 +6,8 @@
#include "ares_dns.h"
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <functional>
#include <sstream>
@ -389,5 +391,30 @@ void NameInfoCallback(void *data, int status, int timeouts,
if (verbose) std::cerr << "NameInfoCallback(" << *result << ")" << std::endl;
}
TempFile::TempFile(const std::string& contents)
: filename_(tempnam(nullptr, "ares")) {
if (!filename_) {
std::cerr << "Error: failed to generate temporary filename" << std::endl;
return;
}
FILE *f = fopen(filename_, "w");
if (!f) {
std::cerr << "Error: failed to create temporary file " << filename_ << std::endl;
return;
}
int rc = fwrite(contents.data(), 1, contents.size(), f);
if (rc < (int)contents.size()) {
std::cerr << "Error: failed to store data in temporary file " << filename_ << std::endl;
}
fclose(f);
}
TempFile::~TempFile() {
if (filename_) {
unlink(filename_);
free(filename_);
}
}
} // namespace test
} // namespace ares

@ -223,6 +223,41 @@ void SearchCallback(void *data, int status, int timeouts,
void NameInfoCallback(void *data, int status, int timeouts,
char *node, char *service);
// RAII class for a temporary file with the given contents.
class TempFile {
public:
TempFile(const std::string& contents);
~TempFile();
const char *filename() const {
return filename_;
}
private:
char *filename_;
};
// RAII class for a temporary environment variable value.
class EnvValue {
public:
EnvValue(const char *name, const char *value) : name_(name), restore_(false) {
char *original = getenv(name);
if (original) {
restore_ = true;
original_ = original;
}
setenv(name_.c_str(), value, 1);
}
~EnvValue() {
if (restore_) {
setenv(name_.c_str(), original_.c_str(), 1);
} else {
unsetenv(name_.c_str());
}
}
private:
std::string name_;
bool restore_;
std::string original_;
};
} // namespace test
} // namespace ares

Loading…
Cancel
Save