test_base.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*************************************************************************
  2. * Copyright (C) [2019] by Cambricon, Inc. All rights reserved
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  15. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. * THE SOFTWARE.
  19. *************************************************************************/
  20. #include "test_base.hpp"
  21. #include <unistd.h>
  22. #include <string.h>
  23. #include <cerrno>
  24. #include <string>
  25. #include <utility>
  26. #include "cnstream_logging.hpp"
  27. extern int errno;
  28. std::string GetExePath() {
  29. char path[PATH_MAX_LENGTH];
  30. int cnt = readlink("/proc/self/exe", path, PATH_MAX_LENGTH);
  31. if (cnt < 0 || cnt >= PATH_MAX_LENGTH) {
  32. return "";
  33. }
  34. for (int i = cnt - 1; i >= 0; --i) {
  35. if ('/' == path[i]) {
  36. path[i + 1] = '\0';
  37. break;
  38. }
  39. }
  40. std::string result(path);
  41. return result;
  42. }
  43. void CheckExePath(const std::string& path) {
  44. if (path.size() == 0) {
  45. LOGF_IF(COREUNITEST, 0 != errno) << std::string(strerror(errno));
  46. LOGF(COREUNITEST) << "length of exe path is larger than " << PATH_MAX_LENGTH;
  47. }
  48. }
  49. std::pair<int, std::string> CreateTempFile(const std::string& filename_prefix) {
  50. char filename[1024];
  51. if (filename_prefix.size() > 1024 - 7) {
  52. LOGF(COREUNITEST) << "filename_prefix is too long, must be less than " << 1024 - 7 << std::endl;
  53. }
  54. strncpy(filename, filename_prefix.c_str(), filename_prefix.size());
  55. strncpy(filename + filename_prefix.size(), "XXXXXX", 6);
  56. filename[filename_prefix.size() + 6] = '\0';
  57. int fd = mkstemp(filename);
  58. LOGF_IF(COREUNITEST, -1 == fd) << "Create temporary file for BuildPipelineByJSONFile test case failed! "
  59. << strerror(errno);
  60. return std::make_pair(fd, std::string(filename));
  61. }