testutil.h raw
1 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. See the AUTHORS file for names of contributors.
4
5 #ifndef STORAGE_LEVELDB_UTIL_TESTUTIL_H_
6 #define STORAGE_LEVELDB_UTIL_TESTUTIL_H_
7
8 #include "helpers/memenv/memenv.h"
9 #include "leveldb/env.h"
10 #include "leveldb/slice.h"
11 #include "util/random.h"
12
13 namespace leveldb {
14 namespace test {
15
16 // Store in *dst a random string of length "len" and return a Slice that
17 // references the generated data.
18 Slice RandomString(Random* rnd, int len, std::string* dst);
19
20 // Return a random key with the specified length that may contain interesting
21 // characters (e.g. \x00, \xff, etc.).
22 std::string RandomKey(Random* rnd, int len);
23
24 // Store in *dst a string of length "len" that will compress to
25 // "N*compressed_fraction" bytes and return a Slice that references
26 // the generated data.
27 Slice CompressibleString(Random* rnd, double compressed_fraction, size_t len,
28 std::string* dst);
29
30 // A wrapper that allows injection of errors.
31 class ErrorEnv : public EnvWrapper {
32 public:
33 bool writable_file_error_;
34 int num_writable_file_errors_;
35
36 ErrorEnv()
37 : EnvWrapper(NewMemEnv(Env::Default())),
38 writable_file_error_(false),
39 num_writable_file_errors_(0) {}
40 ~ErrorEnv() override { delete target(); }
41
42 Status NewWritableFile(const std::string& fname,
43 WritableFile** result) override {
44 if (writable_file_error_) {
45 ++num_writable_file_errors_;
46 *result = nullptr;
47 return Status::IOError(fname, "fake error");
48 }
49 return target()->NewWritableFile(fname, result);
50 }
51
52 Status NewAppendableFile(const std::string& fname,
53 WritableFile** result) override {
54 if (writable_file_error_) {
55 ++num_writable_file_errors_;
56 *result = nullptr;
57 return Status::IOError(fname, "fake error");
58 }
59 return target()->NewAppendableFile(fname, result);
60 }
61 };
62
63 } // namespace test
64 } // namespace leveldb
65
66 #endif // STORAGE_LEVELDB_UTIL_TESTUTIL_H_
67