random_string_test.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2015 The Crashpad Authors. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "util/misc/random_string.h"
  15. #include <sys/types.h>
  16. #include <set>
  17. #include "base/macros.h"
  18. #include "gtest/gtest.h"
  19. namespace crashpad {
  20. namespace test {
  21. namespace {
  22. TEST(RandomString, RandomString) {
  23. // Explicitly list the allowed characters, rather than relying on a range.
  24. // This prevents the test from having any dependency on the character set, so
  25. // that the implementation is free to assume all uppercase letters are
  26. // contiguous as in ASCII.
  27. const std::string allowed_characters("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  28. size_t character_counts[26] = {};
  29. ASSERT_EQ(allowed_characters.size(), arraysize(character_counts));
  30. std::set<std::string> strings;
  31. for (size_t i = 0; i < 256; ++i) {
  32. const std::string random_string = RandomString();
  33. EXPECT_EQ(random_string.size(), 16u);
  34. // Make sure that the string is unique. It is possible, but extremely
  35. // unlikely, for there to be collisions.
  36. auto result = strings.insert(random_string);
  37. EXPECT_TRUE(result.second) << random_string;
  38. for (char c : random_string) {
  39. size_t character_index = allowed_characters.find(c);
  40. // Make sure that no unexpected characters appear.
  41. EXPECT_NE(character_index, std::string::npos) << c;
  42. if (character_index != std::string::npos) {
  43. ++character_counts[character_index];
  44. }
  45. }
  46. }
  47. // Make sure every character appears at least once. It is possible, but
  48. // extremely unlikely, for a character to not appear at all.
  49. for (size_t character_index = 0;
  50. character_index < arraysize(character_counts);
  51. ++character_index) {
  52. EXPECT_GT(character_counts[character_index], 0u)
  53. << allowed_characters[character_index];
  54. }
  55. }
  56. } // namespace
  57. } // namespace test
  58. } // namespace crashpad