scope.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #pragma once
  2. #include <util/generic/string.h>
  3. #include <util/generic/vector.h>
  4. #include <util/system/env.h>
  5. #include <utility>
  6. namespace NTesting {
  7. // @brief Assigns new values to the given environment variables and restores old values upon destruction.
  8. // @note if there was no env variable with given name, it will be set to empty string upon destruction IGNIETFERRO-1486
  9. struct TScopedEnvironment {
  10. TScopedEnvironment(const TString& name, const TString& value)
  11. : PreviousState{1, {name, ::GetEnv(name)}}
  12. {
  13. ::SetEnv(name, value);
  14. }
  15. TScopedEnvironment(const TVector<std::pair<TString, TString>>& vars)
  16. : PreviousState(Reserve(vars.size()))
  17. {
  18. for (const auto& [k, v] : vars) {
  19. PreviousState.emplace_back(k, ::GetEnv(k));
  20. ::SetEnv(k, v);
  21. }
  22. }
  23. ~TScopedEnvironment() {
  24. for (const auto& [k, v] : PreviousState) {
  25. ::SetEnv(k, v);
  26. }
  27. }
  28. TScopedEnvironment(const TScopedEnvironment&) = delete;
  29. TScopedEnvironment& operator=(const TScopedEnvironment&) = delete;
  30. private:
  31. TVector<std::pair<TString, TString>> PreviousState;
  32. };
  33. }