Line data Source code
1 : // Author(s): Frank Stappers 2 : // Copyright: see the accompanying file COPYING or copy at 3 : // https://github.com/mCRL2org/mCRL2/blob/master/COPYING 4 : // 5 : // Distributed under the Boost Software License, Version 1.0. 6 : // (See accompanying file LICENSE_1_0.txt or copy at 7 : // http://www.boost.org/LICENSE_1_0.txt) 8 : // 9 : /// \file mcrl2/utilities/test_utilities.h 10 : /// \brief Utility functions for unit testing 11 : 12 : #ifndef MCRL2_UTILITIES_TEST_UTILITIES_H 13 : #define MCRL2_UTILITIES_TEST_UTILITIES_H 14 : 15 : #include <algorithm> 16 : #include <cctype> 17 : #include <fstream> 18 : #include <sstream> 19 : #include <string> 20 : #include <vector> 21 : 22 : namespace mcrl2 23 : { 24 : 25 : namespace utilities 26 : { 27 : 28 : /// \brief Generate a random alphanumeric character 29 : inline 30 635 : char rand_alnum() 31 : { 32 : char c; 33 : do 34 : { 35 635 : c = static_cast<char>(std::rand()); 36 635 : } while(!std::isalnum(static_cast<unsigned char>(c))); 37 : // The cast to unsigned char, above here, is to ensure that the value passed 38 : // to isalnum is between 0 and 255, which is required by std::isalnum. 39 : // MSVC checks for these bounds in debug mode. 40 152 : return c; 41 : 42 : } 43 : 44 : /// \brief Generate a random string of length n 45 : inline 46 19 : std::string rand_alnum_str(const std::string::size_type n) 47 : { 48 19 : std::string s; 49 19 : s.reserve(n); 50 19 : std::generate_n(std::back_inserter(s), n, rand_alnum); 51 19 : return s; 52 0 : } 53 : 54 : inline 55 19 : bool file_exists(const char *filename) 56 : { 57 19 : std::ifstream ifile(filename); 58 38 : return ifile.good(); 59 19 : } 60 : 61 : /// \brief Get filename with random suffix 62 : /// \warning is prone to race conditions 63 : inline 64 19 : std::string temporary_filename(std::string const& prefix = "") 65 : { 66 38 : std::string basename(prefix + "_" + rand_alnum_str(8)); 67 19 : std::string result = basename ; 68 19 : int suffix = 0; 69 19 : while (file_exists(result.c_str())) 70 : { 71 0 : std::stringstream suffix_s; 72 0 : suffix_s << suffix; 73 0 : result = basename + suffix_s.str(); 74 0 : ++suffix; 75 0 : } 76 38 : return result; 77 19 : } 78 : 79 : } // namespace utilities 80 : 81 : } // namespace mcrl2 82 : 83 : #endif // MCRL2_UTILITIES_TEST_UTILITIES_H