From 9ccb006f61e5b23ed46c8ebf5fedbad337f7e579 Mon Sep 17 00:00:00 2001 From: Sebastian Messmer Date: Sat, 8 Jul 2023 14:48:59 -0700 Subject: [PATCH] - Switch some CI jobs to clang 15 - Fix clang-tidy warnings from Clang 15 --- .clang-tidy | 4 + .github/workflows/main.yaml | 57 ++++---- run-clang-tidy.sh | 6 +- .../implementations/onblocks/BlobOnBlocks.h | 2 +- .../onblocks/BlobStoreOnBlocks.h | 2 +- .../onblocks/datanodestore/DataInnerNode.h | 2 +- .../onblocks/datanodestore/DataLeafNode.cpp | 6 +- .../onblocks/datanodestore/DataLeafNode.h | 2 +- .../onblocks/datanodestore/DataNodeStore.cpp | 2 +- .../onblocks/datanodestore/DataNodeView.h | 2 +- .../onblocks/datatreestore/DataTree.cpp | 62 ++++----- .../onblocks/datatreestore/impl/CachedValue.h | 4 +- .../datatreestore/impl/LeafTraverser.cpp | 54 ++++---- .../ParallelAccessDataTreeStore.cpp | 4 +- .../caching/CachingBlockStore2.cpp | 11 +- .../implementations/caching/cache/Cache.h | 4 +- .../compressing/CompressedBlock.h | 6 +- .../compressing/CompressingBlockStore.h | 2 +- .../compressors/RunLengthEncoding.cpp | 2 +- .../encrypted/EncryptedBlockStore2.h | 8 +- .../inmemory/InMemoryBlockStore2.cpp | 15 +- .../integrity/IntegrityBlockStore2.cpp | 26 ++-- .../integrity/KnownBlockVersions.cpp | 36 ++--- .../low2highlevel/LowToHighLevelBlock.cpp | 6 +- .../low2highlevel/LowToHighLevelBlock.h | 2 +- .../LowToHighLevelBlockStore.cpp | 2 +- .../implementations/mock/MockBlockStore.h | 10 +- .../ondisk/OnDiskBlockStore2.cpp | 8 +- .../ParallelAccessBlockStore.cpp | 2 +- .../implementations/testfake/FakeBlock.h | 2 +- .../testfake/FakeBlockStore.cpp | 14 +- src/blockstore/interface/BlockStore.h | 2 +- src/blockstore/interface/BlockStore2.h | 2 +- .../utils/FileDoesntExistException.cpp | 1 - .../utils/FileDoesntExistException.h | 2 +- src/cpp-utils/assert/backtrace_nonwindows.cpp | 6 +- src/cpp-utils/crypto/RandomPadding.cpp | 4 +- src/cpp-utils/crypto/hash/Hash.cpp | 1 - src/cpp-utils/crypto/kdf/SCryptParameters.cpp | 13 +- src/cpp-utils/crypto/kdf/Scrypt.cpp | 6 +- src/cpp-utils/crypto/symmetric/AEAD_Cipher.h | 4 +- src/cpp-utils/crypto/symmetric/Cipher.h | 4 +- .../testutils/FakeAuthenticatedCipher.h | 10 +- src/cpp-utils/data/Data.cpp | 6 +- src/cpp-utils/data/Data.h | 2 +- src/cpp-utils/data/DataFixture.cpp | 2 +- src/cpp-utils/data/Deserializer.h | 8 +- src/cpp-utils/data/FixedSizeData.h | 4 +- .../io/DontEchoStdinToStdoutRAII.cpp | 1 - src/cpp-utils/io/IOStreamConsole.cpp | 6 +- src/cpp-utils/io/pipestream.h | 8 +- src/cpp-utils/lock/ConditionBarrier.h | 2 +- src/cpp-utils/lock/LockPool.h | 2 +- src/cpp-utils/network/CurlHttpClient.cpp | 10 +- src/cpp-utils/network/CurlHttpClient.h | 2 +- src/cpp-utils/network/FakeHttpClient.cpp | 1 - src/cpp-utils/pointer/unique_ref.h | 4 +- src/cpp-utils/process/SignalCatcher.cpp | 2 +- src/cpp-utils/process/SignalHandler.h | 4 +- src/cpp-utils/process/daemonize.cpp | 4 +- src/cpp-utils/process/subprocess.cpp | 9 +- src/cpp-utils/random/PseudoRandomPool.h | 5 +- src/cpp-utils/random/Random.h | 4 +- src/cpp-utils/random/RandomDataBuffer.h | 2 +- src/cpp-utils/random/RandomGenerator.h | 1 + .../random/RandomGeneratorThread.cpp | 4 +- .../random/ThreadsafeRandomDataBuffer.h | 8 +- src/cpp-utils/system/diskspace.cpp | 2 +- src/cpp-utils/system/env.cpp | 6 +- src/cpp-utils/system/filetime_nonwindows.cpp | 4 +- src/cpp-utils/system/get_total_memory.cpp | 4 +- src/cpp-utils/tempfile/TempFile.cpp | 2 +- src/cpp-utils/testutils/CaptureStderrRAII.h | 4 +- src/cpp-utils/thread/LeftRight.h | 6 +- src/cpp-utils/thread/ThreadSystem.cpp | 2 +- src/cpp-utils/thread/debugging_nonwindows.cpp | 8 +- src/cryfs-cli/CallAfterTimeout.h | 6 +- src/cryfs-cli/Cli.cpp | 18 +-- src/cryfs-cli/VersionChecker.cpp | 2 +- src/cryfs-cli/program_options/Parser.cpp | 14 +- src/cryfs-cli/program_options/utils.cpp | 2 +- src/cryfs-unmount/Cli.cpp | 4 +- src/cryfs-unmount/main_unmount.cpp | 1 - src/cryfs-unmount/program_options/Parser.cpp | 4 +- src/cryfs/impl/config/CryCipher.cpp | 2 +- src/cryfs/impl/config/CryConfigConsole.cpp | 6 +- src/cryfs/impl/config/CryConfigCreator.cpp | 2 +- src/cryfs/impl/config/CryConfigFile.cpp | 2 +- src/cryfs/impl/config/CryConfigLoader.cpp | 3 +- .../impl/config/crypto/CryConfigEncryptor.cpp | 6 +- .../impl/config/crypto/inner/InnerConfig.cpp | 4 +- .../impl/config/crypto/outer/OuterConfig.cpp | 4 +- src/cryfs/impl/filesystem/CryDevice.cpp | 10 +- src/cryfs/impl/filesystem/CryDir.h | 2 +- src/cryfs/impl/filesystem/CryFile.h | 2 +- src/cryfs/impl/filesystem/CryNode.cpp | 4 +- src/cryfs/impl/filesystem/CryNode.h | 2 +- src/cryfs/impl/filesystem/CryOpenFile.h | 2 +- src/cryfs/impl/filesystem/CrySymlink.h | 2 +- .../cachingfsblobstore/CachingFsBlobStore.h | 2 +- .../impl/filesystem/fsblobstore/DirBlob.cpp | 36 ++--- .../impl/filesystem/fsblobstore/DirBlob.h | 2 +- .../impl/filesystem/fsblobstore/FileBlob.cpp | 4 +- .../filesystem/fsblobstore/FsBlobStore.cpp | 4 +- .../filesystem/fsblobstore/FsBlobView.cpp | 1 - .../impl/filesystem/fsblobstore/FsBlobView.h | 2 +- .../filesystem/fsblobstore/SymlinkBlob.cpp | 4 +- .../filesystem/fsblobstore/utils/DirEntry.cpp | 22 +-- .../fsblobstore/utils/DirEntryList.cpp | 2 +- .../parallelaccessfsblobstore/FsBlobRef.h | 2 +- .../ParallelAccessFsBlobStore.cpp | 6 +- .../ParallelAccessFsBlobStore.h | 2 +- src/cryfs/impl/localstate/BasedirMetadata.cpp | 1 - src/cryfs/impl/localstate/LocalStateDir.cpp | 4 +- .../impl/localstate/LocalStateMetadata.cpp | 6 +- src/fspp/fs_interface/Context.h | 14 +- src/fspp/fstest/FsppDeviceTest_Timestamps.h | 2 +- src/fspp/fstest/FsppDirTest_Timestamps.h | 12 +- src/fspp/fstest/FsppFileTest.h | 2 + src/fspp/fstest/FsppNodeTest_Timestamps.h | 14 +- src/fspp/fstest/FsppOpenFileTest.h | 2 +- src/fspp/fstest/testutils/FileSystemTest.h | 5 +- src/fspp/fstest/testutils/FileTest.h | 42 +++--- .../fstest/testutils/TimestampTestUtils.h | 4 +- src/fspp/fuse/Fuse.cpp | 76 +++++------ src/fspp/impl/FilesystemImpl.cpp | 4 +- src/fspp/impl/FilesystemImpl.h | 2 +- src/fspp/impl/FuseOpenFileList.h | 6 +- src/fspp/impl/IdList.h | 2 +- src/fspp/impl/Profiler.h | 2 +- src/gitversion/VersionCompare.cpp | 18 +-- src/gitversion/gitversion.cpp | 2 +- src/parallelaccessstore/ParallelAccessStore.h | 16 +-- src/stats/main.cpp | 8 +- .../implementations/onblocks/BigBlobsTest.cpp | 4 +- .../onblocks/BlobReadWriteTest.cpp | 12 +- .../implementations/onblocks/BlobSizeTest.cpp | 4 +- .../onblocks/BlobStoreTest.cpp | 4 +- .../datanodestore/DataInnerNodeTest.cpp | 12 +- .../datanodestore/DataLeafNodeTest.cpp | 22 +-- .../datanodestore/DataNodeStoreTest.cpp | 8 +- .../datanodestore/DataNodeViewTest.cpp | 10 +- .../datatreestore/DataTreeStoreTest.cpp | 6 +- .../DataTreeTest_NumStoredBytes.cpp | 16 +-- .../DataTreeTest_Performance.cpp | 8 +- .../DataTreeTest_ResizeByTraversing.cpp | 16 +-- .../DataTreeTest_ResizeNumBytes.cpp | 16 +-- .../datatreestore/LeafTraverserTest.cpp | 6 +- .../onblocks/utils/CeilDivisionTest.cpp | 2 +- .../onblocks/utils/CeilLogTest.cpp | 2 +- .../onblocks/utils/IntPowTest.cpp | 2 +- .../onblocks/utils/MaxZeroSubtractionTest.cpp | 4 +- .../CachingBlockStore2Test_Specific.cpp | 2 + .../cache/CacheTest_MoveConstructor.cpp | 6 +- .../caching/cache/PeriodicTaskTest.cpp | 10 +- .../cache/QueueMapTest_MoveConstructor.cpp | 12 +- .../caching/cache/testutils/QueueMapTest.cpp | 2 +- .../caching/cache/testutils/QueueMapTest.h | 4 +- .../compressors/testutils/CompressorTest.cpp | 8 +- .../EncryptedBlockStoreTest_Specific.cpp | 2 + .../IntegrityBlockStoreTest_Specific.cpp | 21 +-- .../integrity/KnownBlockVersionsTest.cpp | 14 +- .../ondisk/OnDiskBlockStoreTest_Specific.cpp | 2 + .../ParallelAccessBlockStoreTest_Specific.cpp | 2 + test/blockstore/interface/BlockStore2Test.cpp | 4 +- test/blockstore/interface/BlockStoreTest.cpp | 4 +- test/blockstore/testutils/BlockStore2Test.h | 62 ++++----- .../testutils/BlockStoreTest_Data.h | 2 +- .../testutils/BlockStoreTest_Size.h | 18 +-- test/cpp-utils/assert/assert_debug_test.cpp | 2 +- test/cpp-utils/assert/assert_release_test.cpp | 2 +- test/cpp-utils/assert/backtrace_test.cpp | 8 +- test/cpp-utils/assert/exit_signal.cpp | 7 +- test/cpp-utils/crypto/hash/HashTest.cpp | 28 ++-- .../crypto/kdf/SCryptParametersTest.cpp | 34 ++--- .../cpp-utils/crypto/symmetric/CipherTest.cpp | 28 ++-- test/cpp-utils/data/DataFixtureTest.cpp | 20 +-- test/cpp-utils/data/DataTest.cpp | 57 ++++---- test/cpp-utils/data/FixedSizeDataTest.cpp | 46 +++---- .../data/SerializationHelperTest.cpp | 2 +- test/cpp-utils/either_test.cpp | 128 +++++++++--------- test/cpp-utils/io/ConsoleTest.h | 2 +- .../io/DontEchoStdinToStdoutRAIITest.cpp | 2 +- test/cpp-utils/logging/LoggingTest.cpp | 10 +- .../cpp-utils/logging/testutils/LoggingTest.h | 2 +- test/cpp-utils/network/FakeHttpClientTest.cpp | 1 - test/cpp-utils/pointer/cast_test.cpp | 36 ++--- .../pointer/optional_ownership_ptr_test.cpp | 12 +- test/cpp-utils/pointer/unique_ref_test.cpp | 94 ++++++------- test/cpp-utils/process/SignalCatcherTest.cpp | 42 +++--- test/cpp-utils/process/SignalHandlerTest.cpp | 18 +-- test/cpp-utils/process/exit_status.cpp | 2 +- test/cpp-utils/system/EnvTest.cpp | 11 +- test/cpp-utils/system/FiletimeTest.cpp | 6 +- test/cpp-utils/system/GetTotalMemoryTest.cpp | 2 +- test/cpp-utils/system/HomedirTest.cpp | 28 ++-- test/cpp-utils/system/TimeTest.cpp | 10 +- test/cpp-utils/tempfile/TempDirTest.cpp | 12 +- test/cpp-utils/tempfile/TempFileTest.cpp | 34 ++--- test/cpp-utils/thread/LeftRightTest.cpp | 2 +- test/cpp-utils/thread/debugging_test.cpp | 6 +- test/cpp-utils/value_type/ValueTypeTest.cpp | 60 ++++---- test/cryfs-cli/CliTest_IntegrityCheck.cpp | 12 +- test/cryfs-cli/CliTest_Setup.cpp | 10 +- test/cryfs-cli/CliTest_WrongEnvironment.cpp | 6 +- test/cryfs-cli/EnvironmentTest.cpp | 14 +- test/cryfs-cli/program_options/ParserTest.cpp | 74 +++++----- .../program_options/ProgramOptionsTest.cpp | 54 ++++---- test/cryfs-cli/program_options/UtilsTest.cpp | 60 ++++---- test/cryfs-cli/testutils/CliTest.h | 6 +- test/cryfs/impl/config/CompatibilityTest.cpp | 2 +- test/cryfs/impl/config/CryCipherTest.cpp | 10 +- .../impl/config/CryConfigConsoleTest.cpp | 8 +- .../impl/config/CryConfigCreatorTest.cpp | 42 +++--- test/cryfs/impl/config/CryConfigFileTest.cpp | 6 +- .../cryfs/impl/config/CryConfigLoaderTest.cpp | 26 ++-- test/cryfs/impl/config/CryConfigTest.cpp | 52 +++---- .../CryPasswordBasedKeyProviderTest.cpp | 2 +- .../CryPresetPasswordBasedKeyProviderTest.cpp | 2 +- .../crypto/CryConfigEncryptorFactoryTest.cpp | 8 +- .../config/crypto/CryConfigEncryptorTest.cpp | 24 ++-- .../inner/ConcreteInnerEncryptorTest.cpp | 18 +-- .../config/crypto/inner/InnerConfigTest.cpp | 16 +-- .../config/crypto/outer/OuterConfigTest.cpp | 16 +-- .../crypto/outer/OuterEncryptorTest.cpp | 14 +- test/cryfs/impl/filesystem/CryFsTest.cpp | 4 +- .../localstate/LocalStateMetadataTest.cpp | 10 +- test/fspp/fuse/access/FuseAccessErrorTest.cpp | 2 +- .../fuse/access/testutils/FuseAccessTest.cpp | 4 +- .../FuseCreateAndOpenErrorTest.cpp | 4 +- .../FuseCreateAndOpenFileDescriptorTest.cpp | 2 +- .../fuse/fdatasync/FuseFdatasyncErrorTest.cpp | 2 +- .../fdatasync/testutils/FuseFdatasyncTest.cpp | 4 +- test/fspp/fuse/flush/FuseFlushErrorTest.cpp | 2 +- .../fuse/flush/testutils/FuseFlushTest.cpp | 2 +- test/fspp/fuse/fstat/FuseFstatErrorTest.cpp | 2 +- test/fspp/fuse/fsync/FuseFsyncErrorTest.cpp | 2 +- .../fuse/fsync/testutils/FuseFsyncTest.cpp | 4 +- .../fuse/ftruncate/FuseFTruncateErrorTest.cpp | 2 +- .../ftruncate/testutils/FuseFTruncateTest.cpp | 4 +- test/fspp/fuse/lstat/FuseLstatErrorTest.cpp | 4 +- .../fuse/lstat/FuseLstatReturnAtimeTest.cpp | 4 +- .../fuse/lstat/FuseLstatReturnCtimeTest.cpp | 4 +- .../fuse/lstat/FuseLstatReturnGidTest.cpp | 4 +- .../fuse/lstat/FuseLstatReturnModeTest.cpp | 2 +- .../fuse/lstat/FuseLstatReturnMtimeTest.cpp | 4 +- .../fuse/lstat/FuseLstatReturnNlinkTest.cpp | 4 +- .../fuse/lstat/FuseLstatReturnSizeTest.cpp | 4 +- .../fuse/lstat/FuseLstatReturnUidTest.cpp | 4 +- .../fuse/lstat/testutils/FuseLstatTest.cpp | 4 +- test/fspp/fuse/mkdir/FuseMkdirErrorTest.cpp | 4 +- .../fuse/mkdir/testutils/FuseMkdirTest.cpp | 4 +- test/fspp/fuse/openFile/FuseOpenErrorTest.cpp | 4 +- .../openFile/FuseOpenFileDescriptorTest.cpp | 2 +- test/fspp/fuse/read/FuseReadErrorTest.cpp | 2 + .../fuse/readDir/FuseReadDirErrorTest.cpp | 4 +- .../readDir/testutils/FuseReadDirTest.cpp | 10 +- test/fspp/fuse/rename/FuseRenameErrorTest.cpp | 2 +- .../fuse/rename/testutils/FuseRenameTest.cpp | 4 +- test/fspp/fuse/rmdir/FuseRmdirErrorTest.cpp | 2 +- .../fuse/rmdir/testutils/FuseRmdirTest.cpp | 4 +- test/fspp/fuse/statfs/FuseStatfsErrorTest.cpp | 4 +- .../statfs/FuseStatfsReturnBavailTest.cpp | 2 +- .../fuse/statfs/FuseStatfsReturnBfreeTest.cpp | 2 +- .../statfs/FuseStatfsReturnBlocksTest.cpp | 2 +- .../fuse/statfs/FuseStatfsReturnBsizeTest.cpp | 2 +- .../fuse/statfs/FuseStatfsReturnFfreeTest.cpp | 2 +- .../fuse/statfs/FuseStatfsReturnFilesTest.cpp | 2 +- .../statfs/FuseStatfsReturnNamemaxTest.cpp | 2 +- .../fuse/statfs/testutils/FuseStatfsTest.cpp | 4 +- .../fuse/truncate/FuseTruncateErrorTest.cpp | 2 +- .../truncate/testutils/FuseTruncateTest.cpp | 4 +- test/fspp/fuse/unlink/FuseUnlinkErrorTest.cpp | 2 +- .../fuse/unlink/testutils/FuseUnlinkTest.cpp | 4 +- .../fuse/utimens/FuseUtimensErrorTest.cpp | 2 +- .../utimens/testutils/FuseUtimensTest.cpp | 2 +- test/fspp/fuse/write/FuseWriteErrorTest.cpp | 2 + test/fspp/impl/FuseOpenFileListTest.cpp | 26 ++-- test/fspp/impl/IdListTest.cpp | 30 ++-- test/fspp/testutils/FuseTest.h | 2 +- test/fspp/testutils/FuseThread.cpp | 2 +- test/gitversion/ParserTest.cpp | 42 +++--- 282 files changed, 1435 insertions(+), 1398 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 3c684d72..65a1b828 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -16,6 +16,9 @@ Checks: | -cert-err60-cpp, -bugprone-macro-parentheses, -bugprone-exception-escape, + -bugprone-easily-swappable-parameters, + -bugprone-implicit-widening-of-multiplication-result, + -bugprone-narrowing-conversions, -cppcoreguidelines-owning-memory, -cppcoreguidelines-no-malloc, -cppcoreguidelines-pro-type-const-cast, @@ -30,6 +33,7 @@ Checks: | -cppcoreguidelines-macro-usage, -cppcoreguidelines-non-private-member-variables-in-classes, -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-narrowing-conversions, -clang-analyzer-optin.cplusplus.VirtualCall, -clang-analyzer-cplusplus.NewDeleteLeaks, -misc-macro-parentheses, diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index be4b1d32..73687d1a 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -180,9 +180,9 @@ jobs: - name: Local dependencies os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 libomp5-15 libomp-15-dev build_type: RelWithDebInfo extra_cmake_flags: -DDEPENDENCY_CONFIG=../cmake-utils/DependenciesFromLocalSystem.cmake extra_cxxflags: "" @@ -193,9 +193,9 @@ jobs: - name: Local dependencies os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 libomp5-15 libomp-15-dev build_type: RelWithDebInfo extra_cmake_flags: -DDEPENDENCY_CONFIG=../cmake-utils/DependenciesFromLocalSystem.cmake extra_cxxflags: "" @@ -218,9 +218,9 @@ jobs: - name: Werror clang os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 libomp5-15 libomp-15-dev build_type: RelWithDebInfo extra_cmake_flags: -DUSE_WERROR=on extra_cxxflags: "" @@ -230,9 +230,9 @@ jobs: - name: No compatibility os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 libomp5-15 libomp-15-dev build_type: RelWithDebInfo extra_cmake_flags: "" extra_cxxflags: "-DCRYFS_NO_COMPATIBILITY" @@ -241,12 +241,11 @@ jobs: run_build: true run_tests: true - name: ASAN - # TODO Update to ubuntu-22.04 - os: ubuntu-20.04 + os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 libomp5-15 libomp-15-dev build_type: Debug # OpenMP crashes under asan. Disable OpenMP. # TODO is it enough to replace this with omp_num_threads: 1 ? @@ -257,12 +256,11 @@ jobs: run_build: true run_tests: true - name: UBSAN - # TODO Update to ubuntu-22.04 - os: ubuntu-20.04 + os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 libomp5-15 libomp-15-dev build_type: Debug # OpenMP crashes under ubsan. Disable OpenMP. # TODO is it enough to replace this with omp_num_threads: 1 ? @@ -273,12 +271,11 @@ jobs: run_build: true run_tests: true - name: TSAN - # TODO Update to ubuntu-22.04 - os: ubuntu-20.04 + os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 libomp5-15 libomp-15-dev build_type: Debug extra_cmake_flags: "" extra_cxxflags: "-O2 -fsanitize=thread -fno-omit-frame-pointer -fno-omit-frame-pointer -fno-optimize-sibling-calls -fno-common" @@ -290,9 +287,9 @@ jobs: - name: clang-tidy os: ubuntu-22.04 compiler: - cxx: clang++-11 - cc: clang-11 - apt_package: clang-11 clang-tidy-11 libomp5-11 libomp-11-dev + cxx: clang++-15 + cc: clang-15 + apt_package: clang-15 clang-tidy-15 libomp5-15 libomp-15-dev build_type: RelWithDebInfo extra_cmake_flags: "" extra_cxxflags: "" diff --git a/run-clang-tidy.sh b/run-clang-tidy.sh index 61bca456..609c00f8 100755 --- a/run-clang-tidy.sh +++ b/run-clang-tidy.sh @@ -8,9 +8,9 @@ set -e -CXX=clang++-11 -CC=clang-11 -SCRIPT=run-clang-tidy-11.py +CXX=clang++-15 +CC=clang-15 +SCRIPT=run-clang-tidy-15.py export NUMCORES=`nproc` && if [ ! -n "$NUMCORES" ]; then export NUMCORES=`sysctl -n hw.ncpu`; fi echo Using ${NUMCORES} cores diff --git a/src/blobstore/implementations/onblocks/BlobOnBlocks.h b/src/blobstore/implementations/onblocks/BlobOnBlocks.h index e1f0bee3..de3eabfc 100644 --- a/src/blobstore/implementations/onblocks/BlobOnBlocks.h +++ b/src/blobstore/implementations/onblocks/BlobOnBlocks.h @@ -21,7 +21,7 @@ class DataTreeRef; class BlobOnBlocks final: public Blob { public: BlobOnBlocks(cpputils::unique_ref datatree); - ~BlobOnBlocks(); + ~BlobOnBlocks() override; const blockstore::BlockId &blockId() const override; diff --git a/src/blobstore/implementations/onblocks/BlobStoreOnBlocks.h b/src/blobstore/implementations/onblocks/BlobStoreOnBlocks.h index 41d9a33f..606b3fdb 100644 --- a/src/blobstore/implementations/onblocks/BlobStoreOnBlocks.h +++ b/src/blobstore/implementations/onblocks/BlobStoreOnBlocks.h @@ -17,7 +17,7 @@ class ParallelAccessDataTreeStore; class BlobStoreOnBlocks final: public BlobStore { public: BlobStoreOnBlocks(cpputils::unique_ref blockStore, uint64_t physicalBlocksizeBytes); - ~BlobStoreOnBlocks(); + ~BlobStoreOnBlocks() override; cpputils::unique_ref create() override; boost::optional> load(const blockstore::BlockId &blockId) override; diff --git a/src/blobstore/implementations/onblocks/datanodestore/DataInnerNode.h b/src/blobstore/implementations/onblocks/datanodestore/DataInnerNode.h index 357d5608..5bc8e0f1 100644 --- a/src/blobstore/implementations/onblocks/datanodestore/DataInnerNode.h +++ b/src/blobstore/implementations/onblocks/datanodestore/DataInnerNode.h @@ -17,7 +17,7 @@ public: using ChildEntry = DataInnerNode_ChildEntry; DataInnerNode(DataNodeView block); - ~DataInnerNode(); + ~DataInnerNode() override; uint32_t maxStoreableChildren() const; diff --git a/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.cpp b/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.cpp index 62c242c9..a60c47e7 100644 --- a/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.cpp +++ b/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.cpp @@ -26,13 +26,13 @@ DataLeafNode::~DataLeafNode() { unique_ref DataLeafNode::CreateNewNode(BlockStore *blockStore, const DataNodeLayout &layout, Data data) { ASSERT(data.size() <= layout.maxBytesPerLeaf(), "Data passed in is too large for one leaf."); - uint32_t size = data.size(); + const uint32_t size = data.size(); return make_unique_ref(DataNodeView::create(blockStore, layout, DataNode::FORMAT_VERSION_HEADER, 0, size, std::move(data))); } unique_ref DataLeafNode::OverwriteNode(BlockStore *blockStore, const DataNodeLayout &layout, const BlockId &blockId, Data data) { ASSERT(data.size() == layout.maxBytesPerLeaf(), "Data passed in is too large for one leaf."); - uint32_t size = data.size(); + const uint32_t size = data.size(); return make_unique_ref(DataNodeView::overwrite(blockStore, layout, DataNode::FORMAT_VERSION_HEADER, 0, size, blockId, std::move(data))); } @@ -52,7 +52,7 @@ uint32_t DataLeafNode::numBytes() const { void DataLeafNode::resize(uint32_t new_size) { ASSERT(new_size <= maxStoreableBytes(), "Trying to resize to a size larger than the maximal size"); - uint32_t old_size = node().Size(); + const uint32_t old_size = node().Size(); if (new_size < old_size) { fillDataWithZeroesFromTo(new_size, old_size); } diff --git a/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.h b/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.h index e14bbf7c..bde3abe4 100644 --- a/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.h +++ b/src/blobstore/implementations/onblocks/datanodestore/DataLeafNode.h @@ -15,7 +15,7 @@ public: static cpputils::unique_ref OverwriteNode(blockstore::BlockStore *blockStore, const DataNodeLayout &layout, const blockstore::BlockId &blockId, cpputils::Data data); DataLeafNode(DataNodeView block); - ~DataLeafNode(); + ~DataLeafNode() override; //Returning uint64_t, because calculations handling this probably need to be done in 64bit to support >4GB blobs. uint64_t maxStoreableBytes() const; diff --git a/src/blobstore/implementations/onblocks/datanodestore/DataNodeStore.cpp b/src/blobstore/implementations/onblocks/datanodestore/DataNodeStore.cpp index 5d04775b..9635db7a 100644 --- a/src/blobstore/implementations/onblocks/datanodestore/DataNodeStore.cpp +++ b/src/blobstore/implementations/onblocks/datanodestore/DataNodeStore.cpp @@ -80,7 +80,7 @@ unique_ref DataNodeStore::overwriteNodeWith(unique_ref targe } void DataNodeStore::remove(unique_ref node) { - BlockId blockId = node->blockId(); + const BlockId blockId = node->blockId(); cpputils::destruct(std::move(node)); remove(blockId); } diff --git a/src/blobstore/implementations/onblocks/datanodestore/DataNodeView.h b/src/blobstore/implementations/onblocks/datanodestore/DataNodeView.h index 3799612e..4dc9e475 100644 --- a/src/blobstore/implementations/onblocks/datanodestore/DataNodeView.h +++ b/src/blobstore/implementations/onblocks/datanodestore/DataNodeView.h @@ -67,7 +67,7 @@ public: static DataNodeView create(blockstore::BlockStore *blockStore, const DataNodeLayout &layout, uint16_t formatVersion, uint8_t depth, uint32_t size, cpputils::Data data) { ASSERT(data.size() <= layout.datasizeBytes(), "Data is too large for node"); - cpputils::Data serialized = serialize_(layout, formatVersion, depth, size, std::move(data)); + const cpputils::Data serialized = serialize_(layout, formatVersion, depth, size, std::move(data)); ASSERT(serialized.size() == layout.blocksizeBytes(), "Wrong block size"); auto block = blockStore->create(serialized); return DataNodeView(std::move(block)); diff --git a/src/blobstore/implementations/onblocks/datatreestore/DataTree.cpp b/src/blobstore/implementations/onblocks/datatreestore/DataTree.cpp index 43e7d7fb..1f187cc5 100644 --- a/src/blobstore/implementations/onblocks/datatreestore/DataTree.cpp +++ b/src/blobstore/implementations/onblocks/datatreestore/DataTree.cpp @@ -51,7 +51,7 @@ const BlockId &DataTree::blockId() const { void DataTree::flush() const { // By grabbing a lock, we ensure that all modifying functions don't run currently and are therefore flushed. // It's only a shared lock, because this doesn't modify the tree structure. - shared_lock lock(_treeStructureMutex); + const shared_lock lock(_treeStructureMutex); // We also have to flush the root node _rootNode->flush(); } @@ -59,7 +59,7 @@ void DataTree::flush() const { unique_ref DataTree::releaseRootNode() { // Lock also ensures that the root node is currently set (traversing unsets it temporarily) // It's a unique lock because this "modifies" tree structure by changing _rootNode. - unique_lock lock(_treeStructureMutex); + const unique_lock lock(_treeStructureMutex); return std::move(_rootNode); } @@ -74,13 +74,13 @@ uint32_t DataTree::numNodes() const { } uint32_t DataTree::numLeaves() const { - shared_lock lock(_treeStructureMutex); + const shared_lock lock(_treeStructureMutex); return _getOrComputeSizeCache().numLeaves; } uint64_t DataTree::numBytes() const { - shared_lock lock(_treeStructureMutex); + const shared_lock lock(_treeStructureMutex); return _numBytes(); } @@ -107,11 +107,11 @@ DataTree::SizeCache DataTree::_computeSizeCache(const DataNode &node) const { } const DataInnerNode &inner = dynamic_cast(node); - uint32_t numLeavesInLeftChildren = static_cast(inner.numChildren()-1) * _leavesPerFullChild(inner); - uint64_t numBytesInLeftChildren = numLeavesInLeftChildren * _nodeStore->layout().maxBytesPerLeaf(); + const uint32_t numLeavesInLeftChildren = static_cast(inner.numChildren()-1) * _leavesPerFullChild(inner); + const uint64_t numBytesInLeftChildren = numLeavesInLeftChildren * _nodeStore->layout().maxBytesPerLeaf(); auto lastChild = _nodeStore->load(inner.readLastChild().blockId()); ASSERT(lastChild != none, "Couldn't load last child"); - SizeCache sizeInRightChild = _computeSizeCache(**lastChild); + const SizeCache sizeInRightChild = _computeSizeCache(**lastChild); return SizeCache { numLeavesInLeftChildren + sizeInRightChild.numLeaves, @@ -136,16 +136,16 @@ void DataTree::_traverseLeavesByByteIndices(uint64_t beginByte, uint64_t sizeByt return; } - uint64_t endByte = beginByte + sizeBytes; - uint64_t _maxBytesPerLeaf = maxBytesPerLeaf(); - uint32_t firstLeaf = beginByte / _maxBytesPerLeaf; - uint32_t endLeaf = utils::ceilDivision(endByte, _maxBytesPerLeaf); + const uint64_t endByte = beginByte + sizeBytes; + const uint64_t _maxBytesPerLeaf = maxBytesPerLeaf(); + const uint32_t firstLeaf = beginByte / _maxBytesPerLeaf; + const uint32_t endLeaf = utils::ceilDivision(endByte, _maxBytesPerLeaf); bool blobIsGrowingFromThisTraversal = false; auto _onExistingLeaf = [&onExistingLeaf, beginByte, endByte, endLeaf, _maxBytesPerLeaf, &blobIsGrowingFromThisTraversal] (uint32_t leafIndex, bool isRightBorderLeaf, LeafHandle leafHandle) { - uint64_t indexOfFirstLeafByte = leafIndex * _maxBytesPerLeaf; + const uint64_t indexOfFirstLeafByte = leafIndex * _maxBytesPerLeaf; ASSERT(endByte > indexOfFirstLeafByte, "Traversal went too far right"); - uint32_t dataBegin = utils::maxZeroSubtraction(beginByte, indexOfFirstLeafByte); - uint32_t dataEnd = std::min(_maxBytesPerLeaf, endByte - indexOfFirstLeafByte); + const uint32_t dataBegin = utils::maxZeroSubtraction(beginByte, indexOfFirstLeafByte); + const uint32_t dataEnd = std::min(_maxBytesPerLeaf, endByte - indexOfFirstLeafByte); // If we are traversing exactly until the last leaf, then the last leaf wasn't resized by the traversal and might have a wrong size. We have to fix it. if (isRightBorderLeaf) { ASSERT(leafIndex == endLeaf-1, "If we traversed further right, this wouldn't be the right border leaf."); @@ -160,10 +160,10 @@ void DataTree::_traverseLeavesByByteIndices(uint64_t beginByte, uint64_t sizeByt auto _onCreateLeaf = [&onCreateLeaf, _maxBytesPerLeaf, beginByte, firstLeaf, endByte, endLeaf, &blobIsGrowingFromThisTraversal, readOnlyTraversal] (uint32_t leafIndex) -> Data { ASSERT(!readOnlyTraversal, "Cannot create leaves in a read-only traversal"); blobIsGrowingFromThisTraversal = true; - uint64_t indexOfFirstLeafByte = leafIndex * _maxBytesPerLeaf; + const uint64_t indexOfFirstLeafByte = leafIndex * _maxBytesPerLeaf; ASSERT(endByte > indexOfFirstLeafByte, "Traversal went too far right"); - uint32_t dataBegin = utils::maxZeroSubtraction(beginByte, indexOfFirstLeafByte); - uint32_t dataEnd = std::min(_maxBytesPerLeaf, endByte - indexOfFirstLeafByte); + const uint32_t dataBegin = utils::maxZeroSubtraction(beginByte, indexOfFirstLeafByte); + const uint32_t dataEnd = std::min(_maxBytesPerLeaf, endByte - indexOfFirstLeafByte); ASSERT(leafIndex == firstLeaf || dataBegin == 0, "Only the leftmost leaf can have a gap on the left."); ASSERT(leafIndex == endLeaf-1 || dataEnd == _maxBytesPerLeaf, "Only the rightmost leaf can have a gap on the right"); Data data = onCreateLeaf(indexOfFirstLeafByte + dataBegin, dataEnd-dataBegin); @@ -195,11 +195,11 @@ uint32_t DataTree::_leavesPerFullChild(const DataInnerNode &root) const { } void DataTree::resizeNumBytes(uint64_t newNumBytes) { - std::unique_lock lock(_treeStructureMutex); + const std::unique_lock lock(_treeStructureMutex); - uint32_t newNumLeaves = std::max(UINT64_C(1), utils::ceilDivision(newNumBytes, _nodeStore->layout().maxBytesPerLeaf())); - uint32_t newLastLeafSize = newNumBytes - (newNumLeaves-1) * _nodeStore->layout().maxBytesPerLeaf(); - uint32_t maxChildrenPerInnerNode = _nodeStore->layout().maxChildrenPerInnerNode(); + const uint32_t newNumLeaves = std::max(UINT64_C(1), utils::ceilDivision(newNumBytes, _nodeStore->layout().maxBytesPerLeaf())); + const uint32_t newLastLeafSize = newNumBytes - (newNumLeaves-1) * _nodeStore->layout().maxBytesPerLeaf(); + const uint32_t maxChildrenPerInnerNode = _nodeStore->layout().maxChildrenPerInnerNode(); auto onExistingLeaf = [newLastLeafSize] (uint32_t /*index*/, bool /*isRightBorderLeaf*/, LeafHandle leafHandle) { auto leaf = leafHandle.node(); // This is only called, if the new last leaf was already existing @@ -214,10 +214,10 @@ void DataTree::resizeNumBytes(uint64_t newNumBytes) { auto onBacktrackFromSubtree = [this, newNumLeaves, maxChildrenPerInnerNode] (DataInnerNode* node) { // This is only called for the right border nodes of the new tree. // When growing size, the following is a no-op. When shrinking, we're deleting the children that aren't needed anymore. - uint32_t maxLeavesPerChild = utils::intPow(static_cast(maxChildrenPerInnerNode), (static_cast(node->depth())-1)); - uint32_t neededNodesOnChildLevel = utils::ceilDivision(newNumLeaves, maxLeavesPerChild); - uint32_t neededSiblings = utils::ceilDivision(neededNodesOnChildLevel, maxChildrenPerInnerNode); - uint32_t neededChildrenForRightBorderNode = neededNodesOnChildLevel - (neededSiblings-1) * maxChildrenPerInnerNode; + const uint32_t maxLeavesPerChild = utils::intPow(static_cast(maxChildrenPerInnerNode), (static_cast(node->depth())-1)); + const uint32_t neededNodesOnChildLevel = utils::ceilDivision(newNumLeaves, maxLeavesPerChild); + const uint32_t neededSiblings = utils::ceilDivision(neededNodesOnChildLevel, maxChildrenPerInnerNode); + const uint32_t neededChildrenForRightBorderNode = neededNodesOnChildLevel - (neededSiblings-1) * maxChildrenPerInnerNode; ASSERT(neededChildrenForRightBorderNode <= node->numChildren(), "Node has too few children"); // All children to the right of the new right-border-node are removed including their subtree. while(node->numChildren() > neededChildrenForRightBorderNode) { @@ -238,12 +238,12 @@ uint64_t DataTree::maxBytesPerLeaf() const { } uint8_t DataTree::depth() const { - shared_lock lock(_treeStructureMutex); + const shared_lock lock(_treeStructureMutex); return _rootNode->depth(); } void DataTree::readBytes(void *target, uint64_t offset, uint64_t count) const { - shared_lock lock(_treeStructureMutex); + const shared_lock lock(_treeStructureMutex); const uint64_t _size = _numBytes(); if(offset > _size || offset + count > _size) { @@ -256,10 +256,10 @@ void DataTree::readBytes(void *target, uint64_t offset, uint64_t count) const { } Data DataTree::readAllBytes() const { - shared_lock lock(_treeStructureMutex); + const shared_lock lock(_treeStructureMutex); //TODO Querying numBytes can be inefficient. Is this possible without a call to size()? - uint64_t count = _numBytes(); + const uint64_t count = _numBytes(); Data result(count); _doReadBytes(result.data(), 0, count); @@ -267,7 +267,7 @@ Data DataTree::readAllBytes() const { } uint64_t DataTree::tryReadBytes(void *target, uint64_t offset, uint64_t count) const { - shared_lock lock(_treeStructureMutex); + const shared_lock lock(_treeStructureMutex); auto result = _tryReadBytes(target, offset, count); return result; } @@ -294,7 +294,7 @@ void DataTree::_doReadBytes(void *target, uint64_t offset, uint64_t count) const } void DataTree::writeBytes(const void *source, uint64_t offset, uint64_t count) { - unique_lock lock(_treeStructureMutex); + const unique_lock lock(_treeStructureMutex); auto onExistingLeaf = [source, offset, count] (uint64_t indexOfFirstLeafByte, LeafHandle leaf, uint32_t leafDataOffset, uint32_t leafDataSize) { ASSERT(indexOfFirstLeafByte+leafDataOffset>=offset && indexOfFirstLeafByte-offset+leafDataOffset <= count && indexOfFirstLeafByte-offset+leafDataOffset+leafDataSize <= count, "Reading from source out of bounds"); diff --git a/src/blobstore/implementations/onblocks/datatreestore/impl/CachedValue.h b/src/blobstore/implementations/onblocks/datatreestore/impl/CachedValue.h index 323db3e2..6042f5d9 100644 --- a/src/blobstore/implementations/onblocks/datatreestore/impl/CachedValue.h +++ b/src/blobstore/implementations/onblocks/datatreestore/impl/CachedValue.h @@ -18,14 +18,14 @@ public: T getOrCompute(std::function compute) { boost::upgrade_lock readLock(_mutex); if (_cache == boost::none) { - boost::upgrade_to_unique_lock writeLock(readLock); + const boost::upgrade_to_unique_lock writeLock(readLock); _cache = compute(); } return *_cache; } void update(std::function*)> func) { - boost::unique_lock writeLock(_mutex); + const boost::unique_lock writeLock(_mutex); func(&_cache); } diff --git a/src/blobstore/implementations/onblocks/datatreestore/impl/LeafTraverser.cpp b/src/blobstore/implementations/onblocks/datatreestore/impl/LeafTraverser.cpp index 259ed165..e8288f88 100644 --- a/src/blobstore/implementations/onblocks/datatreestore/impl/LeafTraverser.cpp +++ b/src/blobstore/implementations/onblocks/datatreestore/impl/LeafTraverser.cpp @@ -37,8 +37,8 @@ namespace blobstore { // beginIndexdepth()); - bool increaseTreeDepth = endIndex > maxLeavesForDepth; + const uint32_t maxLeavesForDepth = _maxLeavesForTreeDepth((*root)->depth()); + const bool increaseTreeDepth = endIndex > maxLeavesForDepth; ASSERT(!_readOnlyTraversal || !increaseTreeDepth, "Tried to grow a tree on a read only traversal"); if ((*root)->depth() == 0) { @@ -49,7 +49,7 @@ namespace blobstore { leaf->resize(_nodeStore->layout().maxBytesPerLeaf()); } if (beginIndex == 0 && endIndex >= 1) { - bool isRightBorderLeaf = (endIndex == 1); + const bool isRightBorderLeaf = (endIndex == 1); onExistingLeaf(0, isRightBorderLeaf, LeafHandle(_nodeStore, leaf)); } } else { @@ -119,21 +119,21 @@ namespace blobstore { //TODO Call callbacks for different leaves in parallel. - uint32_t leavesPerChild = _maxLeavesForTreeDepth(root->depth()-1); - uint32_t beginChild = beginIndex/leavesPerChild; - uint32_t endChild = utils::ceilDivision(endIndex, leavesPerChild); + const uint32_t leavesPerChild = _maxLeavesForTreeDepth(root->depth()-1); + const uint32_t beginChild = beginIndex/leavesPerChild; + const uint32_t endChild = utils::ceilDivision(endIndex, leavesPerChild); ASSERT(endChild <= _nodeStore->layout().maxChildrenPerInnerNode(), "Traversal region would need increasing the tree depth. This should have happened before calling this function."); - uint32_t numChildren = root->numChildren(); + const uint32_t numChildren = root->numChildren(); ASSERT(!growLastLeaf || endChild >= numChildren, "Can only grow last leaf if it exists"); ASSERT(!_readOnlyTraversal || endChild <= numChildren, "Can only traverse out of bounds in a read-only traversal"); - bool shouldGrowLastExistingLeaf = growLastLeaf || endChild > numChildren; + const bool shouldGrowLastExistingLeaf = growLastLeaf || endChild > numChildren; // If we traverse outside of the valid region (i.e. usually would only traverse to new leaves and not to the last leaf), // we still have to descend to the last old child to fill it with leaves and grow the last old leaf. if (isLeftBorderOfTraversal && beginChild >= numChildren) { ASSERT(numChildren > 0, "Node doesn't have children."); auto childBlockId = root->readLastChild().blockId(); - uint32_t childOffset = (numChildren-1) * leavesPerChild; + const uint32_t childOffset = (numChildren-1) * leavesPerChild; _traverseExistingSubtree(childBlockId, root->depth()-1, leavesPerChild, leavesPerChild, childOffset, true, false, true, [] (uint32_t /*index*/, bool /*isRightBorderNode*/, LeafHandle /*leaf*/) {ASSERT(false, "We don't actually traverse any leaves.");}, [] (uint32_t /*index*/) -> Data {ASSERT(false, "We don't actually traverse any leaves.");}, @@ -143,12 +143,12 @@ namespace blobstore { // Traverse existing children for (uint32_t childIndex = beginChild; childIndex < std::min(endChild, numChildren); ++childIndex) { auto childBlockId = root->readChild(childIndex).blockId(); - uint32_t childOffset = childIndex * leavesPerChild; - uint32_t localBeginIndex = utils::maxZeroSubtraction(beginIndex, childOffset); - uint32_t localEndIndex = std::min(leavesPerChild, endIndex - childOffset); - bool isFirstChild = (childIndex == beginChild); - bool isLastExistingChild = (childIndex == numChildren - 1); - bool isLastChild = isLastExistingChild && (numChildren == endChild); + const uint32_t childOffset = childIndex * leavesPerChild; + const uint32_t localBeginIndex = utils::maxZeroSubtraction(beginIndex, childOffset); + const uint32_t localEndIndex = std::min(leavesPerChild, endIndex - childOffset); + const bool isFirstChild = (childIndex == beginChild); + const bool isLastExistingChild = (childIndex == numChildren - 1); + const bool isLastChild = isLastExistingChild && (numChildren == endChild); ASSERT(localEndIndex <= leavesPerChild, "We don't want the child to add a tree level because it doesn't have enough space for the traversal."); _traverseExistingSubtree(childBlockId, root->depth()-1, localBeginIndex, localEndIndex, leafOffset + childOffset, isLeftBorderOfTraversal && isFirstChild, isRightBorderNode && isLastChild, shouldGrowLastExistingLeaf && isLastExistingChild, onExistingLeaf, onCreateLeaf, onBacktrackFromSubtree); @@ -158,9 +158,9 @@ namespace blobstore { for (uint32_t childIndex = numChildren; childIndex < endChild; ++childIndex) { ASSERT(!_readOnlyTraversal, "Can't create new children in a read-only traversal"); - uint32_t childOffset = childIndex * leavesPerChild; - uint32_t localBeginIndex = std::min(leavesPerChild, utils::maxZeroSubtraction(beginIndex, childOffset)); - uint32_t localEndIndex = std::min(leavesPerChild, endIndex - childOffset); + const uint32_t childOffset = childIndex * leavesPerChild; + const uint32_t localBeginIndex = std::min(leavesPerChild, utils::maxZeroSubtraction(beginIndex, childOffset)); + const uint32_t localEndIndex = std::min(leavesPerChild, endIndex - childOffset); auto leafCreator = (childIndex >= beginChild) ? onCreateLeaf : _createMaxSizeLeaf(); auto child = _createNewSubtree(localBeginIndex, localEndIndex, leafOffset + childOffset, root->depth() - 1, leafCreator, onBacktrackFromSubtree); root->addChild(*child); @@ -184,18 +184,18 @@ namespace blobstore { return _nodeStore->createNewLeafNode(leafCreator(leafOffset)); } - uint8_t minNeededDepth = utils::ceilLog(_nodeStore->layout().maxChildrenPerInnerNode(), static_cast(endIndex)); + const uint8_t minNeededDepth = utils::ceilLog(_nodeStore->layout().maxChildrenPerInnerNode(), static_cast(endIndex)); ASSERT(depth >= minNeededDepth, "Given tree depth doesn't fit given number of leaves to create."); - uint32_t leavesPerChild = _maxLeavesForTreeDepth(depth-1); - uint32_t beginChild = beginIndex/leavesPerChild; - uint32_t endChild = utils::ceilDivision(endIndex, leavesPerChild); + const uint32_t leavesPerChild = _maxLeavesForTreeDepth(depth-1); + const uint32_t beginChild = beginIndex/leavesPerChild; + const uint32_t endChild = utils::ceilDivision(endIndex, leavesPerChild); vector children; children.reserve(endChild); // TODO Remove redundancy of following two for loops by using min/max for calculating the parameters of the recursive call. // Create gap children (i.e. children before the traversal but after the current size) for (uint32_t childIndex = 0; childIndex < beginChild; ++childIndex) { - uint32_t childOffset = childIndex * leavesPerChild; + const uint32_t childOffset = childIndex * leavesPerChild; auto child = _createNewSubtree(leavesPerChild, leavesPerChild, leafOffset + childOffset, depth - 1, [] (uint32_t /*index*/)->Data {ASSERT(false, "We're only creating gap leaves here, not traversing any.");}, [] (DataInnerNode* /*node*/) {}); @@ -204,9 +204,9 @@ namespace blobstore { } // Create new children that are traversed for(uint32_t childIndex = beginChild; childIndex < endChild; ++childIndex) { - uint32_t childOffset = childIndex * leavesPerChild; - uint32_t localBeginIndex = utils::maxZeroSubtraction(beginIndex, childOffset); - uint32_t localEndIndex = std::min(leavesPerChild, endIndex - childOffset); + const uint32_t childOffset = childIndex * leavesPerChild; + const uint32_t localBeginIndex = utils::maxZeroSubtraction(beginIndex, childOffset); + const uint32_t localEndIndex = std::min(leavesPerChild, endIndex - childOffset); auto child = _createNewSubtree(localBeginIndex, localEndIndex, leafOffset + childOffset, depth - 1, onCreateLeaf, onBacktrackFromSubtree); ASSERT(child->depth() == depth-1, "Created child node has wrong depth"); children.push_back(child->blockId()); @@ -229,7 +229,7 @@ namespace blobstore { function LeafTraverser::_createMaxSizeLeaf() const { ASSERT(!_readOnlyTraversal, "Can't create a new leaf in a read-only traversal"); - uint64_t maxBytesPerLeaf = _nodeStore->layout().maxBytesPerLeaf(); + const uint64_t maxBytesPerLeaf = _nodeStore->layout().maxBytesPerLeaf(); return [maxBytesPerLeaf] (uint32_t /*index*/) -> Data { return Data(maxBytesPerLeaf).FillWithZeroes(); }; diff --git a/src/blobstore/implementations/onblocks/parallelaccessdatatreestore/ParallelAccessDataTreeStore.cpp b/src/blobstore/implementations/onblocks/parallelaccessdatatreestore/ParallelAccessDataTreeStore.cpp index 52f82c75..a9baf467 100644 --- a/src/blobstore/implementations/onblocks/parallelaccessdatatreestore/ParallelAccessDataTreeStore.cpp +++ b/src/blobstore/implementations/onblocks/parallelaccessdatatreestore/ParallelAccessDataTreeStore.cpp @@ -31,12 +31,12 @@ optional> ParallelAccessDataTreeStore::load(const blocks unique_ref ParallelAccessDataTreeStore::createNewTree() { auto dataTree = _dataTreeStore->createNewTree(); - BlockId blockId = dataTree->blockId(); + const BlockId blockId = dataTree->blockId(); return _parallelAccessStore.add(blockId, std::move(dataTree)); // NOLINT (workaround https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82481 ) } void ParallelAccessDataTreeStore::remove(unique_ref tree) { - BlockId blockId = tree->blockId(); + const BlockId blockId = tree->blockId(); return _parallelAccessStore.remove(blockId, std::move(tree)); } diff --git a/src/blockstore/implementations/caching/CachingBlockStore2.cpp b/src/blockstore/implementations/caching/CachingBlockStore2.cpp index b7437364..9bc35a64 100644 --- a/src/blockstore/implementations/caching/CachingBlockStore2.cpp +++ b/src/blockstore/implementations/caching/CachingBlockStore2.cpp @@ -9,7 +9,6 @@ using cpputils::Data; using cpputils::unique_ref; using cpputils::make_unique_ref; using boost::optional; -using boost::none; using std::unique_lock; using std::mutex; @@ -27,7 +26,7 @@ CachingBlockStore2::CachedBlock::~CachedBlock() { _blockStore->_baseBlockStore->store(_blockId, _data); } // remove it from the list of blocks not in the base store, if it's on it - unique_lock lock(_blockStore->_cachedBlocksNotInBaseStoreMutex); + const unique_lock lock(_blockStore->_cachedBlocksNotInBaseStoreMutex); _blockStore->_cachedBlocksNotInBaseStore.erase(_blockId); } @@ -57,7 +56,7 @@ bool CachingBlockStore2::tryCreate(const BlockId &blockId, const Data &data) { return false; } else { _cache.push(blockId, make_unique_ref(this, blockId, data.copy(), true)); - unique_lock lock(_cachedBlocksNotInBaseStoreMutex); + const unique_lock lock(_cachedBlocksNotInBaseStoreMutex); _cachedBlocksNotInBaseStore.insert(blockId); return true; } @@ -69,7 +68,7 @@ bool CachingBlockStore2::remove(const BlockId &blockId) { if (popped != boost::none) { // Remove from base store if it exists in the base store { - unique_lock lock(_cachedBlocksNotInBaseStoreMutex); + const unique_lock lock(_cachedBlocksNotInBaseStoreMutex); if (_cachedBlocksNotInBaseStore.count(blockId) == 0) { const bool existedInBaseStore = _baseBlockStore->remove(blockId); if (!existedInBaseStore) { @@ -125,7 +124,7 @@ void CachingBlockStore2::store(const BlockId &blockId, const Data &data) { uint64_t CachingBlockStore2::numBlocks() const { uint64_t numInCacheButNotInBaseStore = 0; { - unique_lock lock(_cachedBlocksNotInBaseStoreMutex); + const unique_lock lock(_cachedBlocksNotInBaseStoreMutex); numInCacheButNotInBaseStore = _cachedBlocksNotInBaseStore.size(); } return _baseBlockStore->numBlocks() + numInCacheButNotInBaseStore; @@ -141,7 +140,7 @@ uint64_t CachingBlockStore2::blockSizeFromPhysicalBlockSize(uint64_t blockSize) void CachingBlockStore2::forEachBlock(std::function callback) const { { - unique_lock lock(_cachedBlocksNotInBaseStoreMutex); + const unique_lock lock(_cachedBlocksNotInBaseStoreMutex); for (const BlockId &blockId : _cachedBlocksNotInBaseStore) { callback(blockId); } diff --git a/src/blockstore/implementations/caching/cache/Cache.h b/src/blockstore/implementations/caching/cache/Cache.h index eb00dfa3..929da1bd 100644 --- a/src/blockstore/implementations/caching/cache/Cache.h +++ b/src/blockstore/implementations/caching/cache/Cache.h @@ -71,7 +71,7 @@ Cache::~Cache() { template boost::optional Cache::pop(const Key &key) { std::unique_lock lock(_mutex); - cpputils::MutexPoolLock lockEntryFromBeingPopped(&_currentlyFlushingEntries, key, &lock); + const cpputils::MutexPoolLock lockEntryFromBeingPopped(&_currentlyFlushingEntries, key, &lock); auto found = _cachedBlocks.pop(key); if (!found) { @@ -132,7 +132,7 @@ void Cache::_deleteOldEntriesParallel() { template void Cache::_deleteMatchingEntriesAtBeginningParallel(std::function &)> matches) { // Twice the number of cores, so we use full CPU even if half the threads are doing I/O - unsigned int numThreads = 2 * (std::max)(1u, std::thread::hardware_concurrency()); + const unsigned int numThreads = 2 * (std::max)(1u, std::thread::hardware_concurrency()); std::vector> waitHandles; for (unsigned int i = 0; i < numThreads; ++i) { waitHandles.push_back(std::async(std::launch::async, [this, matches] { diff --git a/src/blockstore/implementations/compressing/CompressedBlock.h b/src/blockstore/implementations/compressing/CompressedBlock.h index 56f0f4dc..1edad960 100644 --- a/src/blockstore/implementations/compressing/CompressedBlock.h +++ b/src/blockstore/implementations/compressing/CompressedBlock.h @@ -21,7 +21,7 @@ public: static cpputils::unique_ref Decompress(cpputils::unique_ref baseBlock); CompressedBlock(cpputils::unique_ref baseBlock, cpputils::Data decompressedData); - ~CompressedBlock(); + ~CompressedBlock() override; const void *data() const override; void write(const void *source, uint64_t offset, uint64_t size) override; @@ -80,7 +80,7 @@ CompressedBlock::CompressedBlock(cpputils::unique_ref baseBlo template CompressedBlock::~CompressedBlock() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _compressToBaseBlock(); } @@ -97,7 +97,7 @@ void CompressedBlock::write(const void *source, uint64_t offset, uin template void CompressedBlock::flush() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _compressToBaseBlock(); return _baseBlock->flush(); } diff --git a/src/blockstore/implementations/compressing/CompressingBlockStore.h b/src/blockstore/implementations/compressing/CompressingBlockStore.h index 4fe258f8..482ad9c2 100644 --- a/src/blockstore/implementations/compressing/CompressingBlockStore.h +++ b/src/blockstore/implementations/compressing/CompressingBlockStore.h @@ -12,7 +12,7 @@ template class CompressingBlockStore final: public BlockStore { public: CompressingBlockStore(cpputils::unique_ref baseBlockStore); - ~CompressingBlockStore(); + ~CompressingBlockStore() override; BlockId createBlockId() override; boost::optional> tryCreate(const BlockId &blockId, cpputils::Data data) override; diff --git a/src/blockstore/implementations/compressing/compressors/RunLengthEncoding.cpp b/src/blockstore/implementations/compressing/compressors/RunLengthEncoding.cpp index a6a22936..5fa3ef50 100644 --- a/src/blockstore/implementations/compressing/compressors/RunLengthEncoding.cpp +++ b/src/blockstore/implementations/compressing/compressors/RunLengthEncoding.cpp @@ -84,7 +84,7 @@ namespace blockstore { } Data RunLengthEncoding::_extractData(ostringstream *stream) { - string str = stream->str(); + const string str = stream->str(); Data data(str.size()); std::memcpy(data.data(), str.c_str(), str.size()); return data; diff --git a/src/blockstore/implementations/encrypted/EncryptedBlockStore2.h b/src/blockstore/implementations/encrypted/EncryptedBlockStore2.h index d320ad31..a13830df 100644 --- a/src/blockstore/implementations/encrypted/EncryptedBlockStore2.h +++ b/src/blockstore/implementations/encrypted/EncryptedBlockStore2.h @@ -71,7 +71,7 @@ inline EncryptedBlockStore2::EncryptedBlockStore2(cpputils::unique_ref inline bool EncryptedBlockStore2::tryCreate(const BlockId &blockId, const cpputils::Data &data) { - cpputils::Data encrypted = _encrypt(data); + const cpputils::Data encrypted = _encrypt(data); return _baseBlockStore->tryCreate(blockId, encrypted); } @@ -92,7 +92,7 @@ inline boost::optional EncryptedBlockStore2::load(const template inline void EncryptedBlockStore2::store(const BlockId &blockId, const cpputils::Data &data) { - cpputils::Data encrypted = _encrypt(data); + const cpputils::Data encrypted = _encrypt(data); return _baseBlockStore->store(blockId, encrypted); } @@ -108,7 +108,7 @@ inline uint64_t EncryptedBlockStore2::estimateNumFreeBytes() const { template inline uint64_t EncryptedBlockStore2::blockSizeFromPhysicalBlockSize(uint64_t blockSize) const { - uint64_t baseBlockSize = _baseBlockStore->blockSizeFromPhysicalBlockSize(blockSize); + const uint64_t baseBlockSize = _baseBlockStore->blockSizeFromPhysicalBlockSize(blockSize); if (baseBlockSize <= Cipher::ciphertextSize(0) + sizeof(FORMAT_VERSION_HEADER)) { return 0; } @@ -122,7 +122,7 @@ inline void EncryptedBlockStore2::forEachBlock(std::function inline cpputils::Data EncryptedBlockStore2::_encrypt(const cpputils::Data &data) const { - cpputils::Data encrypted = Cipher::encrypt(static_cast(data.data()), data.size(), _encKey); + const cpputils::Data encrypted = Cipher::encrypt(static_cast(data.data()), data.size(), _encKey); return _prependFormatHeaderToData(encrypted); } diff --git a/src/blockstore/implementations/inmemory/InMemoryBlockStore2.cpp b/src/blockstore/implementations/inmemory/InMemoryBlockStore2.cpp index 539e0795..a065060b 100644 --- a/src/blockstore/implementations/inmemory/InMemoryBlockStore2.cpp +++ b/src/blockstore/implementations/inmemory/InMemoryBlockStore2.cpp @@ -9,7 +9,6 @@ using std::make_pair; using std::vector; using cpputils::Data; using boost::optional; -using boost::none; namespace blockstore { namespace inmemory { @@ -18,7 +17,7 @@ InMemoryBlockStore2::InMemoryBlockStore2() : _blocks() {} bool InMemoryBlockStore2::tryCreate(const BlockId &blockId, const Data &data) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); return _tryCreate(blockId, data); } @@ -28,7 +27,7 @@ bool InMemoryBlockStore2::_tryCreate(const BlockId &blockId, const Data &data) { } bool InMemoryBlockStore2::remove(const BlockId &blockId) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); auto found = _blocks.find(blockId); if (found == _blocks.end()) { // BlockId not found @@ -40,7 +39,7 @@ bool InMemoryBlockStore2::remove(const BlockId &blockId) { } optional InMemoryBlockStore2::load(const BlockId &blockId) const { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); auto found = _blocks.find(blockId); if (found == _blocks.end()) { return boost::none; @@ -49,10 +48,10 @@ optional InMemoryBlockStore2::load(const BlockId &blockId) const { } void InMemoryBlockStore2::store(const BlockId &blockId, const Data &data) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); auto found = _blocks.find(blockId); if (found == _blocks.end()) { - bool success = _tryCreate(blockId, data); + const bool success = _tryCreate(blockId, data); if (!success) { throw std::runtime_error("Could neither save nor create the block in InMemoryBlockStore::store()"); } @@ -63,7 +62,7 @@ void InMemoryBlockStore2::store(const BlockId &blockId, const Data &data) { } uint64_t InMemoryBlockStore2::numBlocks() const { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); return _blocks.size(); } @@ -76,7 +75,7 @@ uint64_t InMemoryBlockStore2::blockSizeFromPhysicalBlockSize(uint64_t blockSize) } vector InMemoryBlockStore2::_allBlockIds() const { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); vector result; result.reserve(_blocks.size()); for (const auto &entry : _blocks) { diff --git a/src/blockstore/implementations/integrity/IntegrityBlockStore2.cpp b/src/blockstore/implementations/integrity/IntegrityBlockStore2.cpp index 2eb363b7..ee099855 100644 --- a/src/blockstore/implementations/integrity/IntegrityBlockStore2.cpp +++ b/src/blockstore/implementations/integrity/IntegrityBlockStore2.cpp @@ -51,8 +51,8 @@ void IntegrityBlockStore2::_checkFormatHeader(const Data &data) const { } bool IntegrityBlockStore2::_checkVersionHeader(const BlockId &blockId, const Data &data) const { - uint32_t clientId = _readClientId(data); - uint64_t version = _readVersion(data); + const uint32_t clientId = _readClientId(data); + const uint64_t version = _readVersion(data); if(!_knownBlockVersions.checkAndUpdateVersion(clientId, blockId, version)) { integrityViolationDetected("The block version number is too low. Did an attacker try to roll back the block or to re-introduce a deleted block?"); @@ -65,7 +65,7 @@ bool IntegrityBlockStore2::_checkVersionHeader(const BlockId &blockId, const Dat bool IntegrityBlockStore2::_checkIdHeader(const BlockId &expectedBlockId, const Data &data) const { // The obvious reason for this is to prevent adversaries from renaming blocks, but storing the block id in this way also // makes the authenticated cipher more robust, see https://libsodium.gitbook.io/doc/secret-key_cryptography/aead#robustness - BlockId actualBlockId = _readBlockId(data); + const BlockId actualBlockId = _readBlockId(data); if (expectedBlockId != actualBlockId) { integrityViolationDetected("The block id is wrong. Did an attacker try to rename some blocks?"); return false; @@ -111,8 +111,8 @@ IntegrityBlockStore2::IntegrityBlockStore2(unique_ref baseBlockStor } bool IntegrityBlockStore2::tryCreate(const BlockId &blockId, const Data &data) { - uint64_t version = _knownBlockVersions.incrementVersion(blockId); - Data dataWithHeader = _prependHeaderToData(blockId, _knownBlockVersions.myClientId(), version, data); + const uint64_t version = _knownBlockVersions.incrementVersion(blockId); + const Data dataWithHeader = _prependHeaderToData(blockId, _knownBlockVersions.myClientId(), version, data); return _baseBlockStore->tryCreate(blockId, dataWithHeader); } @@ -131,11 +131,11 @@ optional IntegrityBlockStore2::load(const BlockId &blockId) const { } #ifndef CRYFS_NO_COMPATIBILITY if (FORMAT_VERSION_HEADER_OLD == _readFormatHeader(*loaded)) { - Data migrated = _migrateBlock(blockId, *loaded); + const Data migrated = _migrateBlock(blockId, *loaded); if (!_checkHeader(blockId, migrated) && !_allowIntegrityViolations) { return optional(none); } - Data content = _removeHeader(migrated); + const Data content = _removeHeader(migrated); const_cast(this)->store(blockId, content); return optional(_removeHeader(migrated)); } @@ -158,8 +158,8 @@ Data IntegrityBlockStore2::_migrateBlock(const BlockId &blockId, const Data &dat #endif void IntegrityBlockStore2::store(const BlockId &blockId, const Data &data) { - uint64_t version = _knownBlockVersions.incrementVersion(blockId); - Data dataWithHeader = _prependHeaderToData(blockId, _knownBlockVersions.myClientId(), version, data); + const uint64_t version = _knownBlockVersions.incrementVersion(blockId); + const Data dataWithHeader = _prependHeaderToData(blockId, _knownBlockVersions.myClientId(), version, data); return _baseBlockStore->store(blockId, dataWithHeader); } @@ -172,7 +172,7 @@ uint64_t IntegrityBlockStore2::estimateNumFreeBytes() const { } uint64_t IntegrityBlockStore2::blockSizeFromPhysicalBlockSize(uint64_t blockSize) const { - uint64_t baseBlockSize = _baseBlockStore->blockSizeFromPhysicalBlockSize(blockSize); + const uint64_t baseBlockSize = _baseBlockStore->blockSizeFromPhysicalBlockSize(blockSize); if (baseBlockSize <= HEADER_LENGTH) { return 0; } @@ -225,9 +225,9 @@ void IntegrityBlockStore2::migrateBlockFromBlockstoreWithoutVersionNumbers(block return; } - uint64_t version = knownBlockVersions->incrementVersion(blockId); - cpputils::Data data = std::move(*data_); - cpputils::Data dataWithHeader = _prependHeaderToData(blockId, knownBlockVersions->myClientId(), version, data); + const uint64_t version = knownBlockVersions->incrementVersion(blockId); + const cpputils::Data data = std::move(*data_); + const cpputils::Data dataWithHeader = _prependHeaderToData(blockId, knownBlockVersions->myClientId(), version, data); baseBlockStore->store(blockId, dataWithHeader); } #endif diff --git a/src/blockstore/implementations/integrity/KnownBlockVersions.cpp b/src/blockstore/implementations/integrity/KnownBlockVersions.cpp index 5f7a35e4..29e79a0f 100644 --- a/src/blockstore/implementations/integrity/KnownBlockVersions.cpp +++ b/src/blockstore/implementations/integrity/KnownBlockVersions.cpp @@ -23,25 +23,27 @@ constexpr uint32_t KnownBlockVersions::CLIENT_ID_FOR_DELETED_BLOCK; KnownBlockVersions::KnownBlockVersions(const bf::path &stateFilePath, uint32_t myClientId) :_integrityViolationOnPreviousRun(false), _knownVersions(), _lastUpdateClientId(), _stateFilePath(stateFilePath), _myClientId(myClientId), _mutex(), _valid(true) { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); ASSERT(_myClientId != CLIENT_ID_FOR_DELETED_BLOCK, "This is not a valid client id"); _loadStateFile(); } KnownBlockVersions::KnownBlockVersions(KnownBlockVersions &&rhs) // NOLINT (intentionally not noexcept) : _integrityViolationOnPreviousRun(false), _knownVersions(), _lastUpdateClientId(), _stateFilePath(), _myClientId(0), _mutex(), _valid(true) { - unique_lock rhsLock(rhs._mutex); - unique_lock lock(_mutex); + const unique_lock rhsLock(rhs._mutex); + const unique_lock lock(_mutex); + // NOLINTBEGIN(cppcoreguidelines-prefer-member-initializer) -- we need to initialize those within the mutexes _integrityViolationOnPreviousRun = rhs._integrityViolationOnPreviousRun; _knownVersions = std::move(rhs._knownVersions); _lastUpdateClientId = std::move(rhs._lastUpdateClientId); _stateFilePath = std::move(rhs._stateFilePath); _myClientId = rhs._myClientId; rhs._valid = false; + // NOLINTEND(cppcoreguidelines-prefer-member-initializer) } KnownBlockVersions::~KnownBlockVersions() { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); if (_valid) { _saveStateFile(); } @@ -56,7 +58,7 @@ bool KnownBlockVersions::integrityViolationOnPreviousRun() const { } bool KnownBlockVersions::checkAndUpdateVersion(uint32_t clientId, const BlockId &blockId, uint64_t version) { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); ASSERT(clientId != CLIENT_ID_FOR_DELETED_BLOCK, "This is not a valid client id"); ASSERT(version > 0, "Version has to be >0"); // Otherwise we wouldn't handle notexisting entries correctly. @@ -81,9 +83,9 @@ bool KnownBlockVersions::checkAndUpdateVersion(uint32_t clientId, const BlockId } uint64_t KnownBlockVersions::incrementVersion(const BlockId &blockId) { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); uint64_t &found = _knownVersions[{_myClientId, blockId}]; // If the entry doesn't exist, this creates it with value 0. - uint64_t newVersion = found + 1; + const uint64_t newVersion = found + 1; if (newVersion == std::numeric_limits::max()) { // It's *very* unlikely we ever run out of version numbers in 64bit...but just to be sure... throw std::runtime_error("Version overflow"); @@ -138,7 +140,7 @@ void KnownBlockVersions::_saveStateFile() const { } std::unordered_map KnownBlockVersions::_deserializeKnownVersions(Deserializer *deserializer) { - uint64_t numEntries = deserializer->readUint64(); + const uint64_t numEntries = deserializer->readUint64(); std::unordered_map result; result.reserve(static_cast(1.2 * numEntries)); // Reserve for factor 1.2 more, so the file system doesn't immediately have to resize it on the first new block. for (uint64_t i = 0 ; i < numEntries; ++i) { @@ -150,7 +152,7 @@ std::unordered_map KnownBlockVersions::_deserializ } void KnownBlockVersions::_serializeKnownVersions(Serializer *serializer, const std::unordered_map& knownVersions) { - uint64_t numEntries = knownVersions.size(); + const uint64_t numEntries = knownVersions.size(); serializer->writeUint64(numEntries); for (const auto &entry : knownVersions) { @@ -159,9 +161,9 @@ void KnownBlockVersions::_serializeKnownVersions(Serializer *serializer, const s } pair KnownBlockVersions::_deserializeKnownVersionsEntry(Deserializer *deserializer) { - uint32_t clientId = deserializer->readUint32(); - BlockId blockId(deserializer->readFixedSizeData()); - uint64_t version = deserializer->readUint64(); + const uint32_t clientId = deserializer->readUint32(); + const BlockId blockId(deserializer->readFixedSizeData()); + const uint64_t version = deserializer->readUint64(); return {{clientId, blockId}, version}; }; @@ -173,7 +175,7 @@ void KnownBlockVersions::_serializeKnownVersionsEntry(Serializer *serializer, co } std::unordered_map KnownBlockVersions::_deserializeLastUpdateClientIds(Deserializer *deserializer) { - uint64_t numEntries = deserializer->readUint64(); + const uint64_t numEntries = deserializer->readUint64(); std::unordered_map result; result.reserve(static_cast(1.2 * numEntries)); // Reserve for factor 1.2 more, so the file system doesn't immediately have to resize it on the first new block. for (uint64_t i = 0 ; i < numEntries; ++i) { @@ -184,7 +186,7 @@ std::unordered_map KnownBlockVersions::_deserializeLastUpdate } void KnownBlockVersions::_serializeLastUpdateClientIds(Serializer *serializer, const std::unordered_map& lastUpdateClientId) { - uint64_t numEntries = lastUpdateClientId.size(); + const uint64_t numEntries = lastUpdateClientId.size(); serializer->writeUint64(numEntries); for (const auto &entry : lastUpdateClientId) { @@ -193,8 +195,8 @@ void KnownBlockVersions::_serializeLastUpdateClientIds(Serializer *serializer, c } pair KnownBlockVersions::_deserializeLastUpdateClientIdEntry(Deserializer *deserializer) { - BlockId blockId(deserializer->readFixedSizeData()); - uint32_t clientId = deserializer->readUint32(); + const BlockId blockId(deserializer->readFixedSizeData()); + const uint32_t clientId = deserializer->readUint32(); return {blockId, clientId}; }; @@ -209,7 +211,7 @@ uint32_t KnownBlockVersions::myClientId() const { } uint64_t KnownBlockVersions::getBlockVersion(uint32_t clientId, const BlockId &blockId) const { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); return _knownVersions.at({clientId, blockId}); } diff --git a/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.cpp b/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.cpp index 7c053ce0..d3833f7e 100644 --- a/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.cpp +++ b/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.cpp @@ -13,7 +13,7 @@ namespace blockstore { namespace lowtohighlevel { optional> LowToHighLevelBlock::TryCreateNew(BlockStore2 *baseBlockStore, const BlockId &blockId, Data data) { - bool success = baseBlockStore->tryCreate(blockId, data); + const bool success = baseBlockStore->tryCreate(blockId, data); if (!success) { return none; } @@ -43,7 +43,7 @@ LowToHighLevelBlock::LowToHighLevelBlock(const BlockId &blockId, Data data, Bloc } LowToHighLevelBlock::~LowToHighLevelBlock() { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); _storeToBaseBlock(); } @@ -58,7 +58,7 @@ void LowToHighLevelBlock::write(const void *source, uint64_t offset, uint64_t co } void LowToHighLevelBlock::flush() { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); _storeToBaseBlock(); } diff --git a/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.h b/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.h index 7606d649..1e973dad 100644 --- a/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.h +++ b/src/blockstore/implementations/low2highlevel/LowToHighLevelBlock.h @@ -28,7 +28,7 @@ public: static boost::optional> Load(BlockStore2 *baseBlockStore, const BlockId &blockId); LowToHighLevelBlock(const BlockId &blockId, cpputils::Data data, BlockStore2 *baseBlockStore); - ~LowToHighLevelBlock(); + ~LowToHighLevelBlock() override; const void *data() const override; void write(const void *source, uint64_t offset, uint64_t count) override; diff --git a/src/blockstore/implementations/low2highlevel/LowToHighLevelBlockStore.cpp b/src/blockstore/implementations/low2highlevel/LowToHighLevelBlockStore.cpp index 885d7564..781409e0 100644 --- a/src/blockstore/implementations/low2highlevel/LowToHighLevelBlockStore.cpp +++ b/src/blockstore/implementations/low2highlevel/LowToHighLevelBlockStore.cpp @@ -44,7 +44,7 @@ optional> LowToHighLevelBlockStore::load(const BlockId &blockI } void LowToHighLevelBlockStore::remove(const BlockId &blockId) { - bool success = _baseBlockStore->remove(blockId); + const bool success = _baseBlockStore->remove(blockId); if (!success) { throw std::runtime_error("Couldn't delete block with id " + blockId.ToString()); } diff --git a/src/blockstore/implementations/mock/MockBlockStore.h b/src/blockstore/implementations/mock/MockBlockStore.h index 7ad4e23a..957ae4b3 100644 --- a/src/blockstore/implementations/mock/MockBlockStore.h +++ b/src/blockstore/implementations/mock/MockBlockStore.h @@ -113,27 +113,27 @@ namespace blockstore { private: void _increaseNumCreatedBlocks() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _createdBlocks += 1; } void _increaseNumLoadedBlocks(const BlockId &blockId) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _loadedBlocks.push_back(blockId); } void _increaseNumRemovedBlocks(const BlockId &blockId) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _removedBlocks.push_back(blockId); } void _increaseNumResizedBlocks(const BlockId &blockId) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _resizedBlocks.push_back(blockId); } void _increaseNumWrittenBlocks(const BlockId &blockId) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _writtenBlocks.push_back(blockId); } diff --git a/src/blockstore/implementations/ondisk/OnDiskBlockStore2.cpp b/src/blockstore/implementations/ondisk/OnDiskBlockStore2.cpp index 295452ae..23b09364 100644 --- a/src/blockstore/implementations/ondisk/OnDiskBlockStore2.cpp +++ b/src/blockstore/implementations/ondisk/OnDiskBlockStore2.cpp @@ -19,7 +19,7 @@ constexpr const char* ALLOWED_BLOCKID_CHARACTERS = "0123456789ABCDEF"; } boost::filesystem::path OnDiskBlockStore2::_getFilepath(const BlockId &blockId) const { - std::string blockIdStr = blockId.ToString(); + const std::string blockIdStr = blockId.ToString(); return _rootDir / blockIdStr.substr(0, PREFIX_LENGTH) / blockIdStr.substr(PREFIX_LENGTH); } @@ -66,7 +66,7 @@ bool OnDiskBlockStore2::remove(const BlockId &blockId) { if (!boost::filesystem::is_regular_file(filepath)) { // TODO Is this branch necessary? return false; } - bool retval = boost::filesystem::remove(filepath); + const bool retval = boost::filesystem::remove(filepath); if (!retval) { cpputils::logging::LOG(cpputils::logging::ERR, "Couldn't find block {} to remove", blockId.ToString()); return false; @@ -121,14 +121,14 @@ void OnDiskBlockStore2::forEachBlock(std::function callb continue; } - std::string blockIdPrefix = prefixDir->path().filename().string(); + const std::string blockIdPrefix = prefixDir->path().filename().string(); if (blockIdPrefix.size() != PREFIX_LENGTH || std::string::npos != blockIdPrefix.find_first_not_of(ALLOWED_BLOCKID_CHARACTERS)) { // directory has wrong length or an invalid character continue; } for (auto block = boost::filesystem::directory_iterator(prefixDir->path()); block != boost::filesystem::directory_iterator(); ++block) { - std::string blockIdPostfix = block->path().filename().string(); + const std::string blockIdPostfix = block->path().filename().string(); if (blockIdPostfix.size() != POSTFIX_LENGTH || std::string::npos != blockIdPostfix.find_first_not_of(ALLOWED_BLOCKID_CHARACTERS)) { // filename has wrong length or an invalid character continue; diff --git a/src/blockstore/implementations/parallelaccess/ParallelAccessBlockStore.cpp b/src/blockstore/implementations/parallelaccess/ParallelAccessBlockStore.cpp index 784baf3a..7c57a34c 100644 --- a/src/blockstore/implementations/parallelaccess/ParallelAccessBlockStore.cpp +++ b/src/blockstore/implementations/parallelaccess/ParallelAccessBlockStore.cpp @@ -60,7 +60,7 @@ unique_ref ParallelAccessBlockStore::overwrite(const BlockId &blockId, Da } void ParallelAccessBlockStore::remove(unique_ref block) { - BlockId blockId = block->blockId(); + const BlockId blockId = block->blockId(); auto block_ref = dynamic_pointer_move(block); ASSERT(block_ref != none, "Block is not a BlockRef"); return _parallelAccessStore.remove(blockId, std::move(*block_ref)); diff --git a/src/blockstore/implementations/testfake/FakeBlock.h b/src/blockstore/implementations/testfake/FakeBlock.h index 6fa0c2f2..65b25ba9 100644 --- a/src/blockstore/implementations/testfake/FakeBlock.h +++ b/src/blockstore/implementations/testfake/FakeBlock.h @@ -14,7 +14,7 @@ class FakeBlockStore; class FakeBlock final: public Block { public: FakeBlock(FakeBlockStore *store, const BlockId &blockId, std::shared_ptr data, bool dirty); - ~FakeBlock(); + ~FakeBlock() override; const void *data() const override; void write(const void *source, uint64_t offset, uint64_t size) override; diff --git a/src/blockstore/implementations/testfake/FakeBlockStore.cpp b/src/blockstore/implementations/testfake/FakeBlockStore.cpp index 48ed49d5..3b009fee 100644 --- a/src/blockstore/implementations/testfake/FakeBlockStore.cpp +++ b/src/blockstore/implementations/testfake/FakeBlockStore.cpp @@ -23,7 +23,7 @@ BlockId FakeBlockStore::createBlockId() { } optional> FakeBlockStore::tryCreate(const BlockId &blockId, Data data) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); auto insert_result = _blocks.emplace(blockId, std::move(data)); if (!insert_result.second) { @@ -35,7 +35,7 @@ optional> FakeBlockStore::tryCreate(const BlockId &blockId, Da } unique_ref FakeBlockStore::overwrite(const BlockId &blockId, Data data) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); auto insert_result = _blocks.emplace(blockId, data.copy()); if (!insert_result.second) { @@ -50,7 +50,7 @@ unique_ref FakeBlockStore::overwrite(const BlockId &blockId, Data data) { } optional> FakeBlockStore::load(const BlockId &blockId) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); return _load(blockId); } @@ -64,8 +64,8 @@ optional> FakeBlockStore::_load(const BlockId &blockId) { } void FakeBlockStore::remove(const BlockId &blockId) { - std::unique_lock lock(_mutex); - int numRemoved = _blocks.erase(blockId); + const std::unique_lock lock(_mutex); + const size_t numRemoved = _blocks.erase(blockId); ASSERT(numRemoved == 1, "Block not found"); } @@ -76,7 +76,7 @@ unique_ref FakeBlockStore::makeFakeBlockFromData(const BlockId &blockId, } void FakeBlockStore::updateData(const BlockId &blockId, const Data &data) { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); auto found = _blocks.find(blockId); if (found == _blocks.end()) { auto insertResult = _blocks.emplace(blockId, data.copy()); @@ -88,7 +88,7 @@ void FakeBlockStore::updateData(const BlockId &blockId, const Data &data) { } uint64_t FakeBlockStore::numBlocks() const { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); return _blocks.size(); } diff --git a/src/blockstore/interface/BlockStore.h b/src/blockstore/interface/BlockStore.h index 9681cccf..f8fb7aac 100644 --- a/src/blockstore/interface/BlockStore.h +++ b/src/blockstore/interface/BlockStore.h @@ -34,7 +34,7 @@ public: virtual void forEachBlock(std::function callback) const = 0; virtual void remove(cpputils::unique_ref block) { - BlockId blockId = block->blockId(); + const BlockId blockId = block->blockId(); cpputils::destruct(std::move(block)); remove(blockId); } diff --git a/src/blockstore/interface/BlockStore2.h b/src/blockstore/interface/BlockStore2.h index 11c08d3a..94c2918b 100644 --- a/src/blockstore/interface/BlockStore2.h +++ b/src/blockstore/interface/BlockStore2.h @@ -33,7 +33,7 @@ public: BlockId create(const cpputils::Data& data) { while (true) { BlockId blockId = createBlockId(); - bool success = tryCreate(blockId, data); + const bool success = tryCreate(blockId, data); if (success) { return blockId; } diff --git a/src/blockstore/utils/FileDoesntExistException.cpp b/src/blockstore/utils/FileDoesntExistException.cpp index 85d7e228..71fced49 100644 --- a/src/blockstore/utils/FileDoesntExistException.cpp +++ b/src/blockstore/utils/FileDoesntExistException.cpp @@ -2,7 +2,6 @@ namespace bf = boost::filesystem; -using std::runtime_error; using std::string; namespace blockstore { diff --git a/src/blockstore/utils/FileDoesntExistException.h b/src/blockstore/utils/FileDoesntExistException.h index d03f57ea..d0f44b7c 100644 --- a/src/blockstore/utils/FileDoesntExistException.h +++ b/src/blockstore/utils/FileDoesntExistException.h @@ -11,7 +11,7 @@ namespace blockstore { class FileDoesntExistException final: public std::runtime_error { public: explicit FileDoesntExistException(const boost::filesystem::path &filepath); - ~FileDoesntExistException(); + ~FileDoesntExistException() override; }; } diff --git a/src/cpp-utils/assert/backtrace_nonwindows.cpp b/src/cpp-utils/assert/backtrace_nonwindows.cpp index 8fbcac60..676311e5 100644 --- a/src/cpp-utils/assert/backtrace_nonwindows.cpp +++ b/src/cpp-utils/assert/backtrace_nonwindows.cpp @@ -39,9 +39,9 @@ void showBacktraceOnCrash() { // the signal handler RAII objects will be initialized on first call (which will register the signal handler) // and destroyed on program exit (which will unregister the signal handler) - static SignalHandlerRAII<&sigsegv_handler> segv(SIGSEGV); - static SignalHandlerRAII<&sigabrt_handler> abrt(SIGABRT); - static SignalHandlerRAII<&sigill_handler> ill(SIGILL); + static const SignalHandlerRAII<&sigsegv_handler> segv(SIGSEGV); + static const SignalHandlerRAII<&sigabrt_handler> abrt(SIGABRT); + static const SignalHandlerRAII<&sigill_handler> ill(SIGILL); } } diff --git a/src/cpp-utils/crypto/RandomPadding.cpp b/src/cpp-utils/crypto/RandomPadding.cpp index 8d9b2229..7df1e16f 100644 --- a/src/cpp-utils/crypto/RandomPadding.cpp +++ b/src/cpp-utils/crypto/RandomPadding.cpp @@ -8,7 +8,7 @@ using namespace cpputils::logging; namespace cpputils { Data RandomPadding::add(const Data &data, size_t targetSize) { - uint32_t size = data.size(); + const uint32_t size = data.size(); if (size >= targetSize - sizeof(size)) { throw std::runtime_error("Data too large. We should increase padding target size."); } @@ -22,7 +22,7 @@ namespace cpputils { } optional RandomPadding::remove(const Data &data) { - uint32_t size = deserialize(data.data()); + const uint32_t size = deserialize(data.data()); if(sizeof(size) + size >= data.size()) { LOG(ERR, "Config file is invalid: Invalid padding."); return boost::none; diff --git a/src/cpp-utils/crypto/hash/Hash.cpp b/src/cpp-utils/crypto/hash/Hash.cpp index 696cdeaf..90b53223 100644 --- a/src/cpp-utils/crypto/hash/Hash.cpp +++ b/src/cpp-utils/crypto/hash/Hash.cpp @@ -2,7 +2,6 @@ #include #include -using cpputils::Random; using CryptoPP::SHA512; namespace cpputils { diff --git a/src/cpp-utils/crypto/kdf/SCryptParameters.cpp b/src/cpp-utils/crypto/kdf/SCryptParameters.cpp index e7a90b34..0d6f4f94 100644 --- a/src/cpp-utils/crypto/kdf/SCryptParameters.cpp +++ b/src/cpp-utils/crypto/kdf/SCryptParameters.cpp @@ -2,7 +2,6 @@ using std::istream; using std::ostream; -using cpputils::Data; namespace cpputils { Data SCryptParameters::serialize() const { @@ -20,9 +19,9 @@ namespace cpputils { SCryptParameters SCryptParameters::deserialize(const cpputils::Data &data) { Deserializer deserializer(&data); - uint64_t n = deserializer.readUint64(); - uint32_t r = deserializer.readUint32(); - uint32_t p = deserializer.readUint32(); + const uint64_t n = deserializer.readUint64(); + const uint32_t r = deserializer.readUint32(); + const uint32_t p = deserializer.readUint32(); Data salt = deserializer.readTailData(); deserializer.finished(); return SCryptParameters(std::move(salt), n, r, p); @@ -30,9 +29,9 @@ namespace cpputils { #ifndef CRYFS_NO_COMPATIBILITY SCryptParameters SCryptParameters::deserializeOldFormat(Deserializer *source) { - uint64_t n = source->readUint64(); - uint32_t r = source->readUint32(); - uint32_t p = source->readUint32(); + const uint64_t n = source->readUint64(); + const uint32_t r = source->readUint32(); + const uint32_t p = source->readUint32(); Data salt = source->readData(); return SCryptParameters(std::move(salt), n, r, p); } diff --git a/src/cpp-utils/crypto/kdf/Scrypt.cpp b/src/cpp-utils/crypto/kdf/Scrypt.cpp index 1fec96ce..52c69826 100644 --- a/src/cpp-utils/crypto/kdf/Scrypt.cpp +++ b/src/cpp-utils/crypto/kdf/Scrypt.cpp @@ -13,7 +13,7 @@ namespace { EncryptionKey _derive(size_t keySize, const std::string& password, const SCryptParameters& kdfParameters) { auto result = EncryptionKey::Null(keySize); - size_t status = CryptoPP::Scrypt().DeriveKey( + const size_t status = CryptoPP::Scrypt().DeriveKey( static_cast(result.data()), result.binaryLength(), reinterpret_cast(password.c_str()), password.size(), static_cast(kdfParameters.salt().data()), kdfParameters.salt().size(), @@ -36,13 +36,13 @@ SCrypt::SCrypt(const SCryptSettings& settingsForNewKeys) } EncryptionKey SCrypt::deriveExistingKey(size_t keySize, const std::string& password, const Data& kdfParameters) { - SCryptParameters parameters = SCryptParameters::deserialize(kdfParameters); + const SCryptParameters parameters = SCryptParameters::deserialize(kdfParameters); auto key = _derive(keySize, password, parameters); return key; } SCrypt::KeyResult SCrypt::deriveNewKey(size_t keySize, const std::string& password) { - SCryptParameters kdfParameters = _createNewSCryptParameters(_settingsForNewKeys); + const SCryptParameters kdfParameters = _createNewSCryptParameters(_settingsForNewKeys); auto key = _derive(keySize, password, kdfParameters); return SCrypt::KeyResult { key, diff --git a/src/cpp-utils/crypto/symmetric/AEAD_Cipher.h b/src/cpp-utils/crypto/symmetric/AEAD_Cipher.h index 42ce3481..32b156ed 100644 --- a/src/cpp-utils/crypto/symmetric/AEAD_Cipher.h +++ b/src/cpp-utils/crypto/symmetric/AEAD_Cipher.h @@ -49,7 +49,7 @@ Data AEADCipher::encrypt(const Cr Data ciphertext(ciphertextSize(plaintextSize)); iv.ToBinary(ciphertext.data()); - CryptoPP::ArraySource(plaintext, plaintextSize, true, + const CryptoPP::ArraySource _1(plaintext, plaintextSize, true, new CryptoPP::AuthenticatedEncryptionFilter(encryption, new CryptoPP::ArraySink(static_cast(ciphertext.data()) + IV_SIZE, ciphertext.size() - IV_SIZE), false, TAG_SIZE @@ -73,7 +73,7 @@ boost::optional AEADCipher: Data plaintext(plaintextSize(ciphertextSize)); try { - CryptoPP::ArraySource(static_cast(ciphertextData), ciphertextSize - IV_SIZE, true, + const CryptoPP::ArraySource _1(static_cast(ciphertextData), ciphertextSize - IV_SIZE, true, new CryptoPP::AuthenticatedDecryptionFilter(decryption, new CryptoPP::ArraySink(static_cast(plaintext.data()), plaintext.size()), CryptoPP::AuthenticatedDecryptionFilter::DEFAULT_FLAGS, TAG_SIZE diff --git a/src/cpp-utils/crypto/symmetric/Cipher.h b/src/cpp-utils/crypto/symmetric/Cipher.h index 4dba2943..436a1576 100644 --- a/src/cpp-utils/crypto/symmetric/Cipher.h +++ b/src/cpp-utils/crypto/symmetric/Cipher.h @@ -19,10 +19,10 @@ public: same_type(UINT32_C(0), X::plaintextSize(UINT32_C(5))); same_type(UINT32_C(0), X::KEYSIZE); same_type(UINT32_C(0), X::STRING_KEYSIZE); - typename X::EncryptionKey key = X::EncryptionKey::CreateKey(Random::OSRandom(), X::KEYSIZE); + const typename X::EncryptionKey key = X::EncryptionKey::CreateKey(Random::OSRandom(), X::KEYSIZE); same_type(Data(0), X::encrypt(static_cast(nullptr), UINT32_C(0), key)); same_type(boost::optional(Data(0)), X::decrypt(static_cast(nullptr), UINT32_C(0), key)); - string name = X::NAME; + const string name = X::NAME; } private: diff --git a/src/cpp-utils/crypto/symmetric/testutils/FakeAuthenticatedCipher.h b/src/cpp-utils/crypto/symmetric/testutils/FakeAuthenticatedCipher.h index f5753359..9f6aa575 100644 --- a/src/cpp-utils/crypto/symmetric/testutils/FakeAuthenticatedCipher.h +++ b/src/cpp-utils/crypto/symmetric/testutils/FakeAuthenticatedCipher.h @@ -59,14 +59,14 @@ namespace cpputils { Data result(ciphertextSize(plaintextSize)); //Add a random IV - uint64_t iv = std::uniform_int_distribution()(random_); + const uint64_t iv = std::uniform_int_distribution()(random_); serialize(result.data(), iv); //Use xor chiffre on plaintext _xor(static_cast(result.dataOffset(sizeof(uint64_t))), plaintext, plaintextSize, encKey.value ^ iv); //Add checksum information - uint64_t checksum = _checksum(static_cast(result.data()), encKey, plaintextSize + sizeof(uint64_t)); + const uint64_t checksum = _checksum(static_cast(result.data()), encKey, plaintextSize + sizeof(uint64_t)); serialize(result.dataOffset(plaintextSize + sizeof(uint64_t)), checksum); return result; @@ -80,14 +80,14 @@ namespace cpputils { } //Check checksum - uint64_t expectedParity = _checksum(ciphertext, encKey, plaintextSize(ciphertextSize) + sizeof(uint64_t)); - uint64_t actualParity = deserialize(ciphertext + plaintextSize(ciphertextSize) + sizeof(uint64_t)); + const uint64_t expectedParity = _checksum(ciphertext, encKey, plaintextSize(ciphertextSize) + sizeof(uint64_t)); + const uint64_t actualParity = deserialize(ciphertext + plaintextSize(ciphertextSize) + sizeof(uint64_t)); if (expectedParity != actualParity) { return boost::none; } //Decrypt xor chiffre from ciphertext - uint64_t iv = deserialize(ciphertext); + const uint64_t iv = deserialize(ciphertext); Data result(plaintextSize(ciphertextSize)); _xor(static_cast(result.data()), ciphertext + sizeof(uint64_t), plaintextSize(ciphertextSize), encKey.value ^ iv); diff --git a/src/cpp-utils/data/Data.cpp b/src/cpp-utils/data/Data.cpp index be94cdbe..3fbc9ab1 100644 --- a/src/cpp-utils/data/Data.cpp +++ b/src/cpp-utils/data/Data.cpp @@ -39,7 +39,7 @@ std::streampos Data::_getStreamSize(istream &stream) { Data Data::LoadFromStream(istream &stream, size_t size) { Data result(size); - stream.read(static_cast(result.data()), result.size()); + stream.read(static_cast(result.data()), static_cast(result.size())); return result; } @@ -47,7 +47,7 @@ Data Data::FromString(const std::string &data, unique_ref allocator) ASSERT(data.size() % 2 == 0, "hex encoded data cannot have odd number of characters"); Data result(data.size() / 2, std::move(allocator)); { - CryptoPP::StringSource _1(data, true, + const CryptoPP::StringSource _1(data, true, new CryptoPP::HexDecoder( new CryptoPP::ArraySink(static_cast(result._data), result.size()) ) @@ -59,7 +59,7 @@ Data Data::FromString(const std::string &data, unique_ref allocator) std::string Data::ToString() const { std::string result; { - CryptoPP::ArraySource _1(static_cast(_data), _size, true, + const CryptoPP::ArraySource _1(static_cast(_data), _size, true, new CryptoPP::HexEncoder( new CryptoPP::StringSink(result) ) diff --git a/src/cpp-utils/data/Data.h b/src/cpp-utils/data/Data.h index 8bad3dc2..5e4f4acb 100644 --- a/src/cpp-utils/data/Data.h +++ b/src/cpp-utils/data/Data.h @@ -184,7 +184,7 @@ inline void Data::StoreToFile(const boost::filesystem::path &filepath) const { } inline void Data::StoreToStream(std::ostream &stream) const { - stream.write(static_cast(_data), _size); + stream.write(static_cast(_data), static_cast(_size)); } inline Data Data::LoadFromStream(std::istream &stream) { diff --git a/src/cpp-utils/data/DataFixture.cpp b/src/cpp-utils/data/DataFixture.cpp index 5f453ecd..27a4ce1c 100644 --- a/src/cpp-utils/data/DataFixture.cpp +++ b/src/cpp-utils/data/DataFixture.cpp @@ -11,7 +11,7 @@ namespace cpputils { val += 1442695040888963407; serialize(result.dataOffset(i*sizeof(unsigned long long int)), val); } - uint64_t alreadyWritten = (size/sizeof(unsigned long long int))*sizeof(unsigned long long int); + const uint64_t alreadyWritten = (size/sizeof(unsigned long long int))*sizeof(unsigned long long int); val *= 6364136223846793005L; val += 1442695040888963407; unsigned char *remainingBytes = reinterpret_cast(&val); diff --git a/src/cpp-utils/data/Deserializer.h b/src/cpp-utils/data/Deserializer.h index cc2c7392..544039fe 100644 --- a/src/cpp-utils/data/Deserializer.h +++ b/src/cpp-utils/data/Deserializer.h @@ -44,7 +44,7 @@ namespace cpputils { } inline bool Deserializer::readBool() { - uint8_t read = readUint8(); + const uint8_t read = readUint8(); if (read == 1) { return true; } else if (read == 0) { @@ -98,7 +98,7 @@ namespace cpputils { } inline Data Deserializer::readData() { - uint64_t size = readUint64(); + const uint64_t size = readUint64(); if (_pos + size > _source->size()) { throw std::runtime_error("Deserialization failed - size overflow"); } @@ -106,7 +106,7 @@ namespace cpputils { } inline Data Deserializer::readTailData() { - uint64_t size = _source->size() - _pos; + const uint64_t size = _source->size() - _pos; return _readData(size); } @@ -134,7 +134,7 @@ namespace cpputils { if (nullbytepos == nullptr) { throw std::runtime_error("Deserialization failed - missing nullbyte for string termination"); } - uint64_t size = static_cast(nullbytepos) - static_cast(_source->dataOffset(_pos)); + const uint64_t size = static_cast(nullbytepos) - static_cast(_source->dataOffset(_pos)); std::string result(static_cast(_source->dataOffset(_pos)), size); _pos += size + 1; return result; diff --git a/src/cpp-utils/data/FixedSizeData.h b/src/cpp-utils/data/FixedSizeData.h index 58833996..9438ecc6 100644 --- a/src/cpp-utils/data/FixedSizeData.h +++ b/src/cpp-utils/data/FixedSizeData.h @@ -61,7 +61,7 @@ FixedSizeData FixedSizeData::FromString(const std::string &data) { ASSERT(data.size() == STRING_LENGTH, "Wrong string size for parsing FixedSizeData"); FixedSizeData result; { - CryptoPP::StringSource _1(data, true, + const CryptoPP::StringSource _1(data, true, new CryptoPP::HexDecoder( new CryptoPP::ArraySink(result._data.data(), BINARY_LENGTH) ) @@ -73,7 +73,7 @@ FixedSizeData FixedSizeData::FromString(const std::string &data) { template std::string FixedSizeData::ToString() const { std::string result; - CryptoPP::ArraySource(_data.data(), BINARY_LENGTH, true, + const CryptoPP::ArraySource _1(_data.data(), BINARY_LENGTH, true, new CryptoPP::HexEncoder( new CryptoPP::StringSink(result) ) diff --git a/src/cpp-utils/io/DontEchoStdinToStdoutRAII.cpp b/src/cpp-utils/io/DontEchoStdinToStdoutRAII.cpp index 224655ab..edf6b0b0 100644 --- a/src/cpp-utils/io/DontEchoStdinToStdoutRAII.cpp +++ b/src/cpp-utils/io/DontEchoStdinToStdoutRAII.cpp @@ -71,7 +71,6 @@ namespace cpputils #endif -using cpputils::make_unique_ref; namespace cpputils { diff --git a/src/cpp-utils/io/IOStreamConsole.cpp b/src/cpp-utils/io/IOStreamConsole.cpp index 48cdd7fa..601c7d3c 100644 --- a/src/cpp-utils/io/IOStreamConsole.cpp +++ b/src/cpp-utils/io/IOStreamConsole.cpp @@ -42,7 +42,7 @@ function(const string &input)> IOStreamConsole::_parseUIn if (parsed == none) { return optional(none); } - unsigned int value = static_cast(*parsed); + const unsigned int value = static_cast(*parsed); if (value < min || value > max) { return optional(none); } @@ -70,7 +70,7 @@ unsigned int IOStreamConsole::ask(const string &question, const vector & for (size_t i = 0; i < options.size(); ++i) { _output << " [" << (i+1) << "] " << options[i] << "\n"; } - int choice = _askForChoice("Your choice [1-" + std::to_string(options.size()) + "]: ", _parseUIntWithMinMax(1, options.size())); + const int choice = _askForChoice("Your choice [1-" + std::to_string(options.size()) + "]: ", _parseUIntWithMinMax(1, options.size())); return choice-1; } @@ -98,7 +98,7 @@ void IOStreamConsole::print(const string &output) { } string IOStreamConsole::askPassword(const string &question) { - DontEchoStdinToStdoutRAII _stdin_input_is_hidden_as_long_as_this_is_in_scope; + const DontEchoStdinToStdoutRAII _stdin_input_is_hidden_as_long_as_this_is_in_scope; _output << question << std::flush; string result; diff --git a/src/cpp-utils/io/pipestream.h b/src/cpp-utils/io/pipestream.h index fa71c373..f0d53c46 100644 --- a/src/cpp-utils/io/pipestream.h +++ b/src/cpp-utils/io/pipestream.h @@ -99,7 +99,7 @@ namespace cpputils { this->d_condition.wait(lock); } if (&this->d_tmp[0] != this->d_current) { - std::streamsize size(this->d_current - &this->d_tmp[0]); + const std::streamsize size(this->d_current - &this->d_tmp[0]); traits_type::copy(this->eback(), &this->d_tmp[0], this->d_current - &this->d_tmp[0]); this->setg(this->eback(), this->eback(), this->eback() + size); @@ -134,14 +134,14 @@ namespace cpputils { this->d_condition.wait(lock); } if (this->d_current != end) { - std::streamsize size(std::min(end - d_current, + const std::streamsize size(std::min(end - d_current, this->pptr() - this->pbase())); traits_type::copy(d_current, this->pbase(), size); this->d_current += size; - std::streamsize remain((this->pptr() - this->pbase()) - size); + const std::streamsize remain((this->pptr() - this->pbase()) - size); traits_type::move(this->pbase(), this->pptr(), remain); this->setp(this->pbase(), this->epptr()); - this->pbump(remain); + this->pbump(static_cast(remain)); this->d_condition.notify_one(); return 0; } diff --git a/src/cpp-utils/lock/ConditionBarrier.h b/src/cpp-utils/lock/ConditionBarrier.h index 459718a8..d7304b4d 100644 --- a/src/cpp-utils/lock/ConditionBarrier.h +++ b/src/cpp-utils/lock/ConditionBarrier.h @@ -26,7 +26,7 @@ namespace cpputils { } void release() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _triggered = true; _cv.notify_all(); } diff --git a/src/cpp-utils/lock/LockPool.h b/src/cpp-utils/lock/LockPool.h index 968770ef..b533efb5 100644 --- a/src/cpp-utils/lock/LockPool.h +++ b/src/cpp-utils/lock/LockPool.h @@ -79,7 +79,7 @@ namespace cpputils { template inline void LockPool::release(const LockName &lockName) { - std::unique_lock mutexLock(_mutex); + const std::unique_lock mutexLock(_mutex); auto found = std::find(_lockedLocks.begin(), _lockedLocks.end(), lockName); ASSERT(found != _lockedLocks.end(), "Lock given to release() was not locked"); _lockedLocks.erase(found); diff --git a/src/cpp-utils/network/CurlHttpClient.cpp b/src/cpp-utils/network/CurlHttpClient.cpp index 49903459..ed404892 100644 --- a/src/cpp-utils/network/CurlHttpClient.cpp +++ b/src/cpp-utils/network/CurlHttpClient.cpp @@ -19,7 +19,7 @@ namespace cpputils { uint32_t CurlHttpClient::CurlInitializerRAII::_refcount = 0; CurlHttpClient::CurlInitializerRAII::CurlInitializerRAII() { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); if (0 == _refcount) { curl_global_init(CURL_GLOBAL_ALL); } @@ -27,7 +27,7 @@ namespace cpputils { } CurlHttpClient::CurlInitializerRAII::~CurlInitializerRAII() { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); _refcount -= 1; if (0 == _refcount) { curl_global_cleanup(); @@ -39,8 +39,8 @@ namespace cpputils { return size * nmemb; } - CurlHttpClient::CurlHttpClient(): curlInitializer(), curl() { - curl = curl_easy_init(); + CurlHttpClient::CurlHttpClient(): curlInitializer(), curl(curl_easy_init()) { + } CurlHttpClient::~CurlHttpClient() { @@ -60,7 +60,7 @@ namespace cpputils { curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, *timeoutMsec); } // Perform the request, res will get the return code - CURLcode res = curl_easy_perform(curl); + const CURLcode res = curl_easy_perform(curl); // Check for errors if (res != CURLE_OK) { throw std::runtime_error("Curl Error " + std::to_string(res) + ": " + curl_easy_strerror(res)); diff --git a/src/cpp-utils/network/CurlHttpClient.h b/src/cpp-utils/network/CurlHttpClient.h index de9d37e7..16b2e23f 100644 --- a/src/cpp-utils/network/CurlHttpClient.h +++ b/src/cpp-utils/network/CurlHttpClient.h @@ -15,7 +15,7 @@ namespace cpputils { public: CurlHttpClient(); - ~CurlHttpClient(); + ~CurlHttpClient() override; std::string get(const std::string &url, boost::optional timeoutMsec = boost::none) override; diff --git a/src/cpp-utils/network/FakeHttpClient.cpp b/src/cpp-utils/network/FakeHttpClient.cpp index 09c730c4..889ae634 100644 --- a/src/cpp-utils/network/FakeHttpClient.cpp +++ b/src/cpp-utils/network/FakeHttpClient.cpp @@ -2,7 +2,6 @@ using std::string; using boost::optional; -using boost::none; namespace cpputils { FakeHttpClient::FakeHttpClient(): _sites() { diff --git a/src/cpp-utils/pointer/unique_ref.h b/src/cpp-utils/pointer/unique_ref.h index 89e0d238..aea11efb 100644 --- a/src/cpp-utils/pointer/unique_ref.h +++ b/src/cpp-utils/pointer/unique_ref.h @@ -161,7 +161,8 @@ inline bool operator!=(const unique_ref &lhs, const unique_ref &rhs) } -namespace std { // NOLINT (intentional change of namespace std) +// NOLINTBEGIN(cert-dcl58-cpp) -- intentional change of namespace std +namespace std { template inline void swap(cpputils::unique_ref& lhs, cpputils::unique_ref& rhs) noexcept { lhs.swap(rhs); @@ -191,5 +192,6 @@ namespace std { // NOLINT (intentional change of namespace std) } }; } +// NOLINTEND(cert-dcl58-cpp) #endif diff --git a/src/cpp-utils/process/SignalCatcher.cpp b/src/cpp-utils/process/SignalCatcher.cpp index ea718a5d..f3dabdd9 100644 --- a/src/cpp-utils/process/SignalCatcher.cpp +++ b/src/cpp-utils/process/SignalCatcher.cpp @@ -123,7 +123,7 @@ SignalCatcher::SignalCatcher(std::initializer_list signals) // - the _signal_occurred flag will not be destructed as long as the signal handler might be called (i.e. as long as _impls lives) _impls.reserve(signals.size()); - for (int signal : signals) { + for (const int signal : signals) { _impls.emplace_back(make_unique(signal, &_signal_occurred)); } } diff --git a/src/cpp-utils/process/SignalHandler.h b/src/cpp-utils/process/SignalHandler.h index ed8752d9..d009f57a 100644 --- a/src/cpp-utils/process/SignalHandler.h +++ b/src/cpp-utils/process/SignalHandler.h @@ -29,7 +29,7 @@ public: std::memset(&new_signal_handler, 0, sizeof(new_signal_handler)); new_signal_handler.sa_handler = handler; // NOLINT(cppcoreguidelines-pro-type-union-access) new_signal_handler.sa_flags = SA_RESTART; - int error = sigfillset(&new_signal_handler.sa_mask); // block all signals while signal handler is running + const int error = sigfillset(&new_signal_handler.sa_mask); // block all signals while signal handler is running if (0 != error) { throw std::runtime_error("Error calling sigfillset. Errno: " + std::to_string(errno)); } @@ -47,7 +47,7 @@ public: private: static void _sigaction(int signal, struct sigaction *new_handler, struct sigaction *old_handler) { - int error = sigaction(signal, new_handler, old_handler); + const int error = sigaction(signal, new_handler, old_handler); if (0 != error) { throw std::runtime_error("Error calling sigaction. Errno: " + std::to_string(errno)); } diff --git a/src/cpp-utils/process/daemonize.cpp b/src/cpp-utils/process/daemonize.cpp index 0f7ccc51..5a80a17b 100644 --- a/src/cpp-utils/process/daemonize.cpp +++ b/src/cpp-utils/process/daemonize.cpp @@ -21,7 +21,7 @@ using namespace cpputils::logging; namespace cpputils { void daemonize() { - pid_t pid = fork(); + const pid_t pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } @@ -34,7 +34,7 @@ void daemonize() { umask(0); // Create a new SID for the child process - pid_t sid = setsid(); + const pid_t sid = setsid(); if (sid < 0) { LOG(ERR, "Failed to get SID for daemon process"); exit(EXIT_FAILURE); diff --git a/src/cpp-utils/process/subprocess.cpp b/src/cpp-utils/process/subprocess.cpp index e53be974..faf19c14 100644 --- a/src/cpp-utils/process/subprocess.cpp +++ b/src/cpp-utils/process/subprocess.cpp @@ -1,10 +1,11 @@ #include "subprocess.h" +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include using std::string; using std::vector; diff --git a/src/cpp-utils/random/PseudoRandomPool.h b/src/cpp-utils/random/PseudoRandomPool.h index f440fccf..28bdef07 100644 --- a/src/cpp-utils/random/PseudoRandomPool.h +++ b/src/cpp-utils/random/PseudoRandomPool.h @@ -2,10 +2,11 @@ #ifndef MESSMER_CPPUTILS_RANDOM_PSEUDORANDOMPOOL_H #define MESSMER_CPPUTILS_RANDOM_PSEUDORANDOMPOOL_H -#include #include "RandomGenerator.h" -#include "ThreadsafeRandomDataBuffer.h" #include "RandomGeneratorThread.h" +#include "ThreadsafeRandomDataBuffer.h" +#include +#include #include namespace cpputils { diff --git a/src/cpp-utils/random/Random.h b/src/cpp-utils/random/Random.h index 49610460..7b456b6b 100644 --- a/src/cpp-utils/random/Random.h +++ b/src/cpp-utils/random/Random.h @@ -12,13 +12,13 @@ namespace cpputils { class Random final { public: static PseudoRandomPool &PseudoRandom() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); static PseudoRandomPool random; return random; } static OSRandomGenerator &OSRandom() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); static OSRandomGenerator random; return random; } diff --git a/src/cpp-utils/random/RandomDataBuffer.h b/src/cpp-utils/random/RandomDataBuffer.h index 026a955c..eddfa98b 100644 --- a/src/cpp-utils/random/RandomDataBuffer.h +++ b/src/cpp-utils/random/RandomDataBuffer.h @@ -39,7 +39,7 @@ namespace cpputils { inline void RandomDataBuffer::add(const Data& newData) { // Concatenate old and new random data - size_t oldSize = size(); + const size_t oldSize = size(); Data combined(oldSize + newData.size()); get(combined.data(), oldSize); std::memcpy(combined.dataOffset(oldSize), newData.data(), newData.size()); diff --git a/src/cpp-utils/random/RandomGenerator.h b/src/cpp-utils/random/RandomGenerator.h index 8cb2dd0e..2fb0cbf6 100644 --- a/src/cpp-utils/random/RandomGenerator.h +++ b/src/cpp-utils/random/RandomGenerator.h @@ -8,6 +8,7 @@ namespace cpputils { class RandomGenerator { public: RandomGenerator(); + virtual ~RandomGenerator() = default; template FixedSizeData getFixedSize(); Data get(size_t size); diff --git a/src/cpp-utils/random/RandomGeneratorThread.cpp b/src/cpp-utils/random/RandomGeneratorThread.cpp index 99804a37..aaa5c7a9 100644 --- a/src/cpp-utils/random/RandomGeneratorThread.cpp +++ b/src/cpp-utils/random/RandomGeneratorThread.cpp @@ -17,9 +17,9 @@ namespace cpputils { bool RandomGeneratorThread::_loopIteration() { _buffer->waitUntilSizeIsLessThan(_minSize); - size_t neededRandomDataSize = _maxSize - _buffer->size(); + const size_t neededRandomDataSize = _maxSize - _buffer->size(); ASSERT(_maxSize > _buffer->size(), "This could theoretically fail if another thread refilled the buffer. But we should be the only refilling thread."); - Data randomData = _generateRandomData(neededRandomDataSize); + const Data randomData = _generateRandomData(neededRandomDataSize); _buffer->add(randomData); return true; // Run another iteration (don't terminate thread) } diff --git a/src/cpp-utils/random/ThreadsafeRandomDataBuffer.h b/src/cpp-utils/random/ThreadsafeRandomDataBuffer.h index 1f822a10..452174ba 100644 --- a/src/cpp-utils/random/ThreadsafeRandomDataBuffer.h +++ b/src/cpp-utils/random/ThreadsafeRandomDataBuffer.h @@ -39,14 +39,14 @@ namespace cpputils { } inline size_t ThreadsafeRandomDataBuffer::size() const { - boost::unique_lock lock(_mutex); + const boost::unique_lock lock(_mutex); return _buffer.size(); } inline void ThreadsafeRandomDataBuffer::get(void *target, size_t numBytes) { size_t alreadyGotten = 0; while (alreadyGotten < numBytes) { - size_t got = _get(static_cast(target)+alreadyGotten, numBytes); + const size_t got = _get(static_cast(target)+alreadyGotten, numBytes); alreadyGotten += got; ASSERT(alreadyGotten <= numBytes, "Got too many bytes"); } @@ -57,14 +57,14 @@ namespace cpputils { _dataAddedCv.wait(lock, [this] { return _buffer.size() > 0; }); - size_t gettableBytes = (std::min)(_buffer.size(), numBytes); + const size_t gettableBytes = (std::min)(_buffer.size(), numBytes); _buffer.get(target, gettableBytes); _dataGottenCv.notify_all(); return gettableBytes; } inline void ThreadsafeRandomDataBuffer::add(const Data& data) { - boost::unique_lock lock(_mutex); + const boost::unique_lock lock(_mutex); _buffer.add(data); _dataAddedCv.notify_all(); } diff --git a/src/cpp-utils/system/diskspace.cpp b/src/cpp-utils/system/diskspace.cpp index 9b10bf9d..88da38a0 100644 --- a/src/cpp-utils/system/diskspace.cpp +++ b/src/cpp-utils/system/diskspace.cpp @@ -11,7 +11,7 @@ namespace cpputils { uint64_t free_disk_space_in_bytes(const bf::path& location) { struct statvfs stat {}; - int result = ::statvfs(location.string().c_str(), &stat); + const int result = ::statvfs(location.string().c_str(), &stat); if (0 != result) { throw std::runtime_error("Error calling statvfs(). Errno: " + std::to_string(errno)); } diff --git a/src/cpp-utils/system/env.cpp b/src/cpp-utils/system/env.cpp index c10cf03a..00554e56 100644 --- a/src/cpp-utils/system/env.cpp +++ b/src/cpp-utils/system/env.cpp @@ -10,14 +10,14 @@ namespace cpputils { void setenv(const char* key, const char* value) { - int retval = ::setenv(key, value, 1); + const int retval = ::setenv(key, value, 1); if (0 != retval) { throw std::runtime_error("Error setting environment variable. Errno: " + std::to_string(errno)); } } void unsetenv(const char* key) { - int retval = ::unsetenv(key); + const int retval = ::unsetenv(key); if (0 != retval) { throw std::runtime_error("Error unsetting environment variable. Errno: " + std::to_string(errno)); } @@ -34,7 +34,7 @@ namespace cpputils { void setenv(const char* key, const char* value) { std::ostringstream command; command << key << "=" << value; - int retval = _putenv(command.str().c_str()); + const int retval = _putenv(command.str().c_str()); if (0 != retval) { throw std::runtime_error("Error setting environment variable. Errno: " + std::to_string(errno)); } diff --git a/src/cpp-utils/system/filetime_nonwindows.cpp b/src/cpp-utils/system/filetime_nonwindows.cpp index 6dccba6a..abc06640 100644 --- a/src/cpp-utils/system/filetime_nonwindows.cpp +++ b/src/cpp-utils/system/filetime_nonwindows.cpp @@ -14,7 +14,7 @@ int set_filetime(const char *filepath, timespec lastAccessTime, timespec lastMod std::array casted_times{}; TIMESPEC_TO_TIMEVAL(&casted_times[0], &lastAccessTime); TIMESPEC_TO_TIMEVAL(&casted_times[1], &lastModificationTime); - int retval = ::utimes(filepath, casted_times.data()); + const int retval = ::utimes(filepath, casted_times.data()); if (0 == retval) { return 0; } else { @@ -24,7 +24,7 @@ int set_filetime(const char *filepath, timespec lastAccessTime, timespec lastMod int get_filetime(const char *filepath, timespec* lastAccessTime, timespec* lastModificationTime) { struct ::stat attrib{}; - int retval = ::stat(filepath, &attrib); + const int retval = ::stat(filepath, &attrib); if (retval != 0) { return errno; } diff --git a/src/cpp-utils/system/get_total_memory.cpp b/src/cpp-utils/system/get_total_memory.cpp index 85f197c7..2347d652 100644 --- a/src/cpp-utils/system/get_total_memory.cpp +++ b/src/cpp-utils/system/get_total_memory.cpp @@ -28,8 +28,8 @@ namespace cpputils { namespace cpputils { namespace system { uint64_t get_total_memory() { - long numRAMPages = sysconf(_SC_PHYS_PAGES); - long pageSize = sysconf(_SC_PAGESIZE); + const long numRAMPages = sysconf(_SC_PHYS_PAGES); + const long pageSize = sysconf(_SC_PAGESIZE); return numRAMPages * pageSize; } } diff --git a/src/cpp-utils/tempfile/TempFile.cpp b/src/cpp-utils/tempfile/TempFile.cpp index 7c4a254c..35482474 100644 --- a/src/cpp-utils/tempfile/TempFile.cpp +++ b/src/cpp-utils/tempfile/TempFile.cpp @@ -11,7 +11,7 @@ namespace cpputils { TempFile::TempFile(const bf::path &path, bool create) : _path(path) { if (create) { - ofstream file(_path.string().c_str()); + const ofstream file(_path.string().c_str()); if (!file.good()) { throw std::runtime_error("Could not create tempfile"); } diff --git a/src/cpp-utils/testutils/CaptureStderrRAII.h b/src/cpp-utils/testutils/CaptureStderrRAII.h index 091331f1..baf0179b 100644 --- a/src/cpp-utils/testutils/CaptureStderrRAII.h +++ b/src/cpp-utils/testutils/CaptureStderrRAII.h @@ -11,8 +11,8 @@ namespace cpputils { class CaptureStderrRAII final { public: - CaptureStderrRAII() { - _oldBuffer = std::cerr.rdbuf(); + CaptureStderrRAII() : _oldBuffer(std::cerr.rdbuf()) { + // Capture stderr to _buffer std::cerr.rdbuf(_buffer.rdbuf()); diff --git a/src/cpp-utils/thread/LeftRight.h b/src/cpp-utils/thread/LeftRight.h index 7b10458a..2ebf482a 100644 --- a/src/cpp-utils/thread/LeftRight.h +++ b/src/cpp-utils/thread/LeftRight.h @@ -38,7 +38,7 @@ public: // wait until any potentially running writers are finished { - std::unique_lock lock(_writeMutex); + const std::unique_lock lock(_writeMutex); } // wait until any potentially running readers are finished @@ -49,7 +49,7 @@ public: template auto read(F&& readFunc) const { - detail::IncrementRAII _increment_counter(&_counters[_foregroundCounterIndex.load()]); // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index) + const detail::IncrementRAII _increment_counter(&_counters[_foregroundCounterIndex.load()]); // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index) if(_inDestruction.load()) { throw std::logic_error("Issued LeftRight::read() after the destructor started running"); @@ -62,7 +62,7 @@ public: // depending on if the first or the second call to writeFunc threw. template auto write(F&& writeFunc) { - std::unique_lock lock(_writeMutex); + const std::unique_lock lock(_writeMutex); if(_inDestruction.load()) { throw std::logic_error("Issued LeftRight::read() after the destructor started running"); diff --git a/src/cpp-utils/thread/ThreadSystem.cpp b/src/cpp-utils/thread/ThreadSystem.cpp index 13a0b0a6..af5032cf 100644 --- a/src/cpp-utils/thread/ThreadSystem.cpp +++ b/src/cpp-utils/thread/ThreadSystem.cpp @@ -24,7 +24,7 @@ namespace cpputils { } ThreadSystem::Handle ThreadSystem::start(function loopIteration, string threadName) { - boost::unique_lock lock(_mutex); + const boost::unique_lock lock(_mutex); auto thread = _startThread(loopIteration, threadName); _runningThreads.push_back(RunningThread{std::move(threadName), std::move(loopIteration), std::move(thread)}); return std::prev(_runningThreads.end()); diff --git a/src/cpp-utils/thread/debugging_nonwindows.cpp b/src/cpp-utils/thread/debugging_nonwindows.cpp index 32bba95b..c32eda2f 100644 --- a/src/cpp-utils/thread/debugging_nonwindows.cpp +++ b/src/cpp-utils/thread/debugging_nonwindows.cpp @@ -26,9 +26,9 @@ void set_thread_name(const char* name) { name_.resize(MAX_NAME_LEN - 1); } #if defined(__APPLE__) - int result = pthread_setname_np(name_.c_str()); + const int result = pthread_setname_np(name_.c_str()); #else - int result = pthread_setname_np(pthread_self(), name_.c_str()); + const int result = pthread_setname_np(pthread_self(), name_.c_str()); #endif if (0 != result) { throw std::runtime_error("Error setting thread name with pthread_setname_np. Code: " + std::to_string(result)); @@ -73,9 +73,9 @@ int pthread_getname_np_gcompat(pthread_t thread, char *name, size_t len) { std::string get_thread_name(pthread_t thread) { std::array name{}; #if defined(__GLIBC__) || defined(__APPLE__) - int result = pthread_getname_np(thread, name.data(), MAX_NAME_LEN); + const int result = pthread_getname_np(thread, name.data(), MAX_NAME_LEN); #else - int result = pthread_getname_np_gcompat(thread, name.data(), MAX_NAME_LEN); + const int result = pthread_getname_np_gcompat(thread, name.data(), MAX_NAME_LEN); #endif if (0 != result) { throw std::runtime_error("Error getting thread name with pthread_getname_np. Code: " + std::to_string(result)); diff --git a/src/cryfs-cli/CallAfterTimeout.h b/src/cryfs-cli/CallAfterTimeout.h index 6052a38c..ce18d04d 100644 --- a/src/cryfs-cli/CallAfterTimeout.h +++ b/src/cryfs-cli/CallAfterTimeout.h @@ -32,7 +32,7 @@ namespace cryfs_cli { } inline void CallAfterTimeout::resetTimer() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); _start = boost::chrono::steady_clock::now(); } @@ -42,12 +42,12 @@ namespace cryfs_cli { } inline boost::chrono::time_point CallAfterTimeout::_targetTime() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); return _start + _timeout; } inline bool CallAfterTimeout::_callCallbackIfTimeout() { - std::unique_lock lock(_mutex); + const std::unique_lock lock(_mutex); if (boost::chrono::steady_clock::now() >= _start + _timeout) { _callback(); return false; // Stop thread diff --git a/src/cryfs-cli/Cli.cpp b/src/cryfs-cli/Cli.cpp index 990ffc6f..c01e50bd 100644 --- a/src/cryfs-cli/Cli.cpp +++ b/src/cryfs-cli/Cli.cpp @@ -72,8 +72,8 @@ using gitversion::VersionCompare; namespace cryfs_cli { Cli::Cli(RandomGenerator &keyGenerator, const SCryptSettings &scryptSettings, shared_ptr console): - _keyGenerator(keyGenerator), _scryptSettings(scryptSettings), _console(), _noninteractive(false), _idleUnmounter(none), _device(none) { - _noninteractive = Environment::isNoninteractive(); + _keyGenerator(keyGenerator), _scryptSettings(scryptSettings), _console(), _noninteractive(Environment::isNoninteractive()), _idleUnmounter(none), _device(none) { + if (_noninteractive) { _console = make_shared(console); } else { @@ -108,7 +108,7 @@ namespace cryfs_cli { } void Cli::_checkForUpdates(unique_ref httpClient) { - VersionChecker versionChecker(httpClient.get()); + const VersionChecker versionChecker(httpClient.get()); optional newestVersion = versionChecker.newestVersion(); if (newestVersion == none) { cout << "Could not check for updates." << endl; @@ -161,7 +161,7 @@ namespace cryfs_cli { } bool Cli::_confirmPassword(cpputils::Console* console, const string &password) { - string confirmPassword = console->askPassword("Confirm Password: "); + const string confirmPassword = console->askPassword("Confirm Password: "); if (password != confirmPassword) { std::cout << "Passwords don't match" << std::endl; return false; @@ -258,7 +258,7 @@ namespace cryfs_cli { void Cli::_runFilesystem(const ProgramOptions &options, std::function onMounted) { try { - LocalStateDir localStateDir(Environment::localStateDir()); + const LocalStateDir localStateDir(Environment::localStateDir()); auto blockStore = make_unique_ref(options.baseDir()); auto config = _loadOrCreateConfig(options, localStateDir); printConfig(config.oldConfig, *config.configFile->config()); @@ -340,7 +340,7 @@ namespace cryfs_cli { if (minutes == none) { return none; } - uint64_t millis = std::llround(60000 * (*minutes)); + const uint64_t millis = std::llround(60000 * (*minutes)); return make_unique_ref(milliseconds(millis), callback, "idlecallback"); } @@ -407,7 +407,7 @@ namespace cryfs_cli { ASSERT(bf::equivalent(dir, tempfile->path().parent_path()), "This function should be called with a file inside the directory"); try { bool found = false; - bf::directory_iterator end; + const bf::directory_iterator end; for (auto iter = bf::directory_iterator(dir); iter != end; ++iter) { if (bf::equivalent(*iter, tempfile->path())) { found = true; @@ -429,7 +429,7 @@ namespace cryfs_cli { } bool Cli::_pathContains(const bf::path &parent, const bf::path &child) { - bf::path absParent = bf::canonical(parent); + const bf::path absParent = bf::canonical(parent); bf::path current = bf::canonical(child); if (absParent.empty() && current.empty()) { return true; @@ -449,7 +449,7 @@ namespace cryfs_cli { try { _showVersion(std::move(httpClient)); - ProgramOptions options = program_options::Parser(argc, argv).parse(CryCiphers::supportedCipherNames()); + const ProgramOptions options = program_options::Parser(argc, argv).parse(CryCiphers::supportedCipherNames()); _sanityChecks(options); _runFilesystem(options, std::move(onMounted)); } catch (const CryfsException &e) { diff --git a/src/cryfs-cli/VersionChecker.cpp b/src/cryfs-cli/VersionChecker.cpp index 8141bdd3..9db8b966 100644 --- a/src/cryfs-cli/VersionChecker.cpp +++ b/src/cryfs-cli/VersionChecker.cpp @@ -47,7 +47,7 @@ namespace cryfs_cli { } optional VersionChecker::_getVersionInfo(HttpClient* httpClient) { - long timeoutMsec = 2000; + const long timeoutMsec = 2000; string response; try { response = httpClient->get("https://www.cryfs.org/version_info.json", timeoutMsec); diff --git a/src/cryfs-cli/program_options/Parser.cpp b/src/cryfs-cli/program_options/Parser.cpp index 771c9ca3..880897c8 100644 --- a/src/cryfs-cli/program_options/Parser.cpp +++ b/src/cryfs-cli/program_options/Parser.cpp @@ -41,7 +41,7 @@ ProgramOptions Parser::parse(const vector &supportedCiphers) const { LOG(WARN, "Passing fuse mount options after a double dash '--' is deprecated. Please pass them directly (e.g. 'cryfs basedir mountdir -o allow_other'"); } - po::variables_map vm = _parseOptionsOrShowHelp(cryfsOptions, supportedCiphers); + const po::variables_map vm = _parseOptionsOrShowHelp(cryfsOptions, supportedCiphers); if (!vm.count("base-dir")) { _showHelpAndExit("Please specify a base directory.", ErrorCode::InvalidArguments); @@ -55,11 +55,11 @@ ProgramOptions Parser::parse(const vector &supportedCiphers) const { if (vm.count("config")) { configfile = bf::absolute(vm["config"].as()); } - bool foreground = vm.count("foreground"); - bool allowFilesystemUpgrade = vm.count("allow-filesystem-upgrade"); - bool allowReplacedFilesystem = vm.count("allow-replaced-filesystem"); - bool createMissingBasedir = vm.count("create-missing-basedir"); - bool createMissingMountpoint = vm.count("create-missing-mountpoint"); + const bool foreground = vm.count("foreground"); + const bool allowFilesystemUpgrade = vm.count("allow-filesystem-upgrade"); + const bool allowReplacedFilesystem = vm.count("allow-replaced-filesystem"); + const bool createMissingBasedir = vm.count("create-missing-basedir"); + const bool createMissingMountpoint = vm.count("create-missing-mountpoint"); optional unmountAfterIdleMinutes = 0.0; // first setting to 0 and then to none is somehow needed to silence a GCC warning from -Wmaybe-uninitialized unmountAfterIdleMinutes = none; if (vm.count("unmount-idle")) { @@ -78,7 +78,7 @@ ProgramOptions Parser::parse(const vector &supportedCiphers) const { if (vm.count("blocksize")) { blocksizeBytes = vm["blocksize"].as(); } - bool allowIntegrityViolations = vm.count("allow-integrity-violations"); + const bool allowIntegrityViolations = vm.count("allow-integrity-violations"); optional missingBlockIsIntegrityViolation = none; if (vm.count("missing-block-is-integrity-violation")) { missingBlockIsIntegrityViolation = vm["missing-block-is-integrity-violation"].as(); diff --git a/src/cryfs-cli/program_options/utils.cpp b/src/cryfs-cli/program_options/utils.cpp index 7064baca..13e9cd75 100644 --- a/src/cryfs-cli/program_options/utils.cpp +++ b/src/cryfs-cli/program_options/utils.cpp @@ -12,7 +12,7 @@ namespace cryfs_cli { namespace program_options { pair, vector> splitAtDoubleDash(const vector &options) { auto doubleDashIterator = std::find(options.begin(), options.end(), string("--")); - vector beforeDoubleDash(options.begin(), doubleDashIterator); + const vector beforeDoubleDash(options.begin(), doubleDashIterator); vector afterDoubleDash; if (doubleDashIterator != options.end() && doubleDashIterator + 1 != options.end()) { afterDoubleDash.reserve(options.size() - beforeDoubleDash.size() - 1); diff --git a/src/cryfs-unmount/Cli.cpp b/src/cryfs-unmount/Cli.cpp index 5832966c..fa408f9c 100644 --- a/src/cryfs-unmount/Cli.cpp +++ b/src/cryfs-unmount/Cli.cpp @@ -20,13 +20,13 @@ void _showVersion() { void Cli::main(int argc, const char **argv) { _showVersion(); - ProgramOptions options = Parser(argc, argv).parse(); + const ProgramOptions options = Parser(argc, argv).parse(); if (!boost::filesystem::exists(options.mountDir())) { throw cryfs::CryfsException("Given mountdir doesn't exist", cryfs::ErrorCode::InaccessibleMountDir); } - bool immediate = options.immediate(); + bool immediate = options.immediate(); // NOLINT(misc-const-correctness) -- this cannot be const because it is modified in a platform-specific ifdef below #if defined(__APPLE__) if (options.immediate()) { std::cerr << "Warning: OSX doesn't support the --immediate flag. Ignoring it."; diff --git a/src/cryfs-unmount/main_unmount.cpp b/src/cryfs-unmount/main_unmount.cpp index e84e3e6f..e8980fcd 100644 --- a/src/cryfs-unmount/main_unmount.cpp +++ b/src/cryfs-unmount/main_unmount.cpp @@ -8,7 +8,6 @@ #include #include "Cli.h" -using std::cerr; using cryfs::ErrorCode; int main(int argc, const char *argv[]) { diff --git a/src/cryfs-unmount/program_options/Parser.cpp b/src/cryfs-unmount/program_options/Parser.cpp index d2613114..798025ff 100644 --- a/src/cryfs-unmount/program_options/Parser.cpp +++ b/src/cryfs-unmount/program_options/Parser.cpp @@ -30,13 +30,13 @@ vector Parser::_argsToVector(int argc, const char **argv) { } ProgramOptions Parser::parse() const { - po::variables_map vm = _parseOptionsOrShowHelp(_options); + const po::variables_map vm = _parseOptionsOrShowHelp(_options); if (!vm.count("mount-dir")) { _showHelpAndExit("Please specify a mount directory.", ErrorCode::InvalidArguments); } bf::path mountDir = vm["mount-dir"].as(); - bool immediate = vm.count("immediate"); + const bool immediate = vm.count("immediate"); return ProgramOptions(std::move(mountDir), immediate); } diff --git a/src/cryfs/impl/config/CryCipher.cpp b/src/cryfs/impl/config/CryCipher.cpp index 6f5ec90e..f3319651 100644 --- a/src/cryfs/impl/config/CryCipher.cpp +++ b/src/cryfs/impl/config/CryCipher.cpp @@ -100,6 +100,6 @@ vector CryCiphers::_buildSupportedCipherNames() { } const vector& CryCiphers::supportedCipherNames() { - static vector supportedCipherNames = _buildSupportedCipherNames(); + static const vector supportedCipherNames = _buildSupportedCipherNames(); return supportedCipherNames; } diff --git a/src/cryfs/impl/config/CryConfigConsole.cpp b/src/cryfs/impl/config/CryConfigConsole.cpp index 6b0d36fd..9c765b2c 100644 --- a/src/cryfs/impl/config/CryConfigConsole.cpp +++ b/src/cryfs/impl/config/CryConfigConsole.cpp @@ -29,7 +29,7 @@ namespace cryfs { bool askAgain = true; while(askAgain) { _console->print("\n"); - unsigned int cipherIndex = _console->ask("Which block cipher do you want to use?", ciphers); + const unsigned int cipherIndex = _console->ask("Which block cipher do you want to use?", ciphers); cipherName = ciphers[cipherIndex]; askAgain = !_showWarningForCipherAndReturnIfOk(cipherName); }; @@ -53,8 +53,8 @@ namespace cryfs { } uint32_t CryConfigConsole::_askBlocksizeBytes() const { - vector sizes = {"4KB", "8KB", "16KB", "32KB", "64KB", "512KB", "1MB", "4MB"}; - unsigned int index = _console->ask("Which block size do you want to use?", sizes); + const vector sizes = {"4KB", "8KB", "16KB", "32KB", "64KB", "512KB", "1MB", "4MB"}; + const unsigned int index = _console->ask("Which block size do you want to use?", sizes); switch(index) { case 0: return 4*1024; case 1: return 8*1024; diff --git a/src/cryfs/impl/config/CryConfigCreator.cpp b/src/cryfs/impl/config/CryConfigCreator.cpp index 2bd72996..98b46161 100644 --- a/src/cryfs/impl/config/CryConfigCreator.cpp +++ b/src/cryfs/impl/config/CryConfigCreator.cpp @@ -30,7 +30,7 @@ namespace cryfs { config.SetFilesystemId(_generateFilesystemID()); auto encryptionKey = _generateEncKey(config.Cipher()); auto localState = LocalStateMetadata::loadOrGenerate(_localStateDir.forFilesystemId(config.FilesystemId()), cpputils::Data::FromString(encryptionKey), allowReplacedFilesystem); - uint32_t myClientId = localState.myClientId(); + const uint32_t myClientId = localState.myClientId(); config.SetEncryptionKey(std::move(encryptionKey)); config.SetExclusiveClientId(_generateExclusiveClientId(missingBlockIsIntegrityViolationFromCommandLine, myClientId)); #ifndef CRYFS_NO_COMPATIBILITY diff --git a/src/cryfs/impl/config/CryConfigFile.cpp b/src/cryfs/impl/config/CryConfigFile.cpp index 185ee3c0..34493fa2 100644 --- a/src/cryfs/impl/config/CryConfigFile.cpp +++ b/src/cryfs/impl/config/CryConfigFile.cpp @@ -74,7 +74,7 @@ void CryConfigFile::save() const { if (_access == Access::ReadOnly) { throw std::logic_error("Tried to save the cryfs.config file while being in read only mode"); } - Data configData = _config.save(); + const Data configData = _config.save(); auto encrypted = _encryptor->encrypt(configData, _config.Cipher()); encrypted.StoreToFile(_path); } diff --git a/src/cryfs/impl/config/CryConfigLoader.cpp b/src/cryfs/impl/config/CryConfigLoader.cpp index c1982582..8debaf61 100644 --- a/src/cryfs/impl/config/CryConfigLoader.cpp +++ b/src/cryfs/impl/config/CryConfigLoader.cpp @@ -20,7 +20,6 @@ using boost::none; using std::shared_ptr; using std::string; using std::shared_ptr; -using gitversion::VersionCompare; using namespace cpputils::logging; namespace cryfs { @@ -59,7 +58,7 @@ either CryConfigLoa } _checkCipher(*config.right()->config()); auto localState = LocalStateMetadata::loadOrGenerate(_localStateDir.forFilesystemId(config.right()->config()->FilesystemId()), cpputils::Data::FromString(config.right()->config()->EncryptionKey()), allowReplacedFilesystem); - uint32_t myClientId = localState.myClientId(); + const uint32_t myClientId = localState.myClientId(); _checkMissingBlocksAreIntegrityViolations(config.right().get(), myClientId); return ConfigLoadResult {std::move(oldConfig), std::move(config.right()), myClientId}; } diff --git a/src/cryfs/impl/config/crypto/CryConfigEncryptor.cpp b/src/cryfs/impl/config/crypto/CryConfigEncryptor.cpp index 5c32f0f2..af63265e 100644 --- a/src/cryfs/impl/config/crypto/CryConfigEncryptor.cpp +++ b/src/cryfs/impl/config/crypto/CryConfigEncryptor.cpp @@ -19,9 +19,9 @@ namespace cryfs { } Data CryConfigEncryptor::encrypt(const Data &plaintext, const string &cipherName) const { - InnerConfig innerConfig = _innerEncryptor(cipherName)->encrypt(plaintext); - Data serializedInnerConfig = innerConfig.serialize(); - OuterConfig outerConfig = _outerEncryptor()->encrypt(serializedInnerConfig); + const InnerConfig innerConfig = _innerEncryptor(cipherName)->encrypt(plaintext); + const Data serializedInnerConfig = innerConfig.serialize(); + const OuterConfig outerConfig = _outerEncryptor()->encrypt(serializedInnerConfig); return outerConfig.serialize(); } diff --git a/src/cryfs/impl/config/crypto/inner/InnerConfig.cpp b/src/cryfs/impl/config/crypto/inner/InnerConfig.cpp index bdd62cc0..bba76ae3 100644 --- a/src/cryfs/impl/config/crypto/inner/InnerConfig.cpp +++ b/src/cryfs/impl/config/crypto/inner/InnerConfig.cpp @@ -32,7 +32,7 @@ namespace cryfs { Deserializer deserializer(&data); try { _checkHeader(&deserializer); - string cipherName = deserializer.readString(); + const string cipherName = deserializer.readString(); auto result = deserializer.readTailData(); deserializer.finished(); return InnerConfig {cipherName, std::move(result)}; @@ -43,7 +43,7 @@ namespace cryfs { } void InnerConfig::_checkHeader(Deserializer *deserializer) { - string header = deserializer->readString(); + const string header = deserializer->readString(); if (header != HEADER) { throw std::runtime_error("Invalid header. Maybe this filesystem was created with a different version of CryFS?"); } diff --git a/src/cryfs/impl/config/crypto/outer/OuterConfig.cpp b/src/cryfs/impl/config/crypto/outer/OuterConfig.cpp index 8041020b..7b7b7327 100644 --- a/src/cryfs/impl/config/crypto/outer/OuterConfig.cpp +++ b/src/cryfs/impl/config/crypto/outer/OuterConfig.cpp @@ -18,7 +18,7 @@ namespace cryfs { const string OuterConfig::HEADER = "cryfs.config;1;scrypt"; void OuterConfig::_checkHeader(Deserializer *deserializer) { - string header = deserializer->readString(); + const string header = deserializer->readString(); if (header != HEADER) { throw std::runtime_error("Invalid header"); } @@ -47,7 +47,7 @@ namespace cryfs { Deserializer deserializer(&data); try { #ifndef CRYFS_NO_COMPATIBILITY - string header = deserializer.readString(); + const string header = deserializer.readString(); if (header == OLD_HEADER) { return _deserializeOldFormat(&deserializer); } else if (header == HEADER) { diff --git a/src/cryfs/impl/filesystem/CryDevice.cpp b/src/cryfs/impl/filesystem/CryDevice.cpp index e3cd7d2c..d8aebcd3 100644 --- a/src/cryfs/impl/filesystem/CryDevice.cpp +++ b/src/cryfs/impl/filesystem/CryDevice.cpp @@ -78,7 +78,7 @@ unique_ref CryDevice::Crea #ifndef CRYFS_NO_COMPATIBILITY unique_ref CryDevice::MigrateOrCreateFsBlobStore(unique_ref blobStore, CryConfigFile *configFile) { - string rootBlobId = configFile->config()->RootBlob(); + const string rootBlobId = configFile->config()->RootBlob(); if ("" == rootBlobId) { return make_unique_ref(std::move(blobStore)); } @@ -252,7 +252,7 @@ optional CryDevice::LoadBlobWithAncestors(const bf // Child entry in directory not found return none; } - BlockId childId = childOpt->blockId(); + const BlockId childId = childOpt->blockId(); auto nextBlob = _fsBlobStore->load(childId); if (nextBlob == none) { throw FuseErrnoException(EIO); // Blob for directory entry not found @@ -273,8 +273,8 @@ optional CryDevice::LoadBlobWithAncestors(const bf CryDevice::statvfs CryDevice::statfs() { callFsActionCallbacks(); - uint64_t numUsedBlocks = _fsBlobStore->numBlocks(); - uint64_t numFreeBlocks = _fsBlobStore->estimateSpaceForNumBlocksLeft(); + const uint64_t numUsedBlocks = _fsBlobStore->numBlocks(); + const uint64_t numFreeBlocks = _fsBlobStore->estimateSpaceForNumBlocksLeft(); statvfs result; result.max_filename_length = 255; // We theoretically support unlimited file name length, but this is default for many Linux file systems, so probably also makes sense for CryFS. @@ -322,7 +322,7 @@ void CryDevice::RemoveBlob(const blockstore::BlockId &blockId) { } BlockId CryDevice::GetOrCreateRootBlobId(CryConfigFile *configFile) { - string root_blockId = configFile->config()->RootBlob(); + const string root_blockId = configFile->config()->RootBlob(); if (root_blockId == "") { // NOLINT (workaround https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82481 ) auto new_blockId = CreateRootBlobAndReturnId(); configFile->config()->SetRootBlob(new_blockId.ToString()); diff --git a/src/cryfs/impl/filesystem/CryDir.h b/src/cryfs/impl/filesystem/CryDir.h index 74343774..c3f37d26 100644 --- a/src/cryfs/impl/filesystem/CryDir.h +++ b/src/cryfs/impl/filesystem/CryDir.h @@ -11,7 +11,7 @@ namespace cryfs { class CryDir final: public fspp::Dir, public CryNode { public: CryDir(CryDevice *device, boost::optional> parent, boost::optional> grandparent, const blockstore::BlockId &blockId); - ~CryDir(); + ~CryDir() override; //TODO return type variance to CryFile/CryDir? cpputils::unique_ref createAndOpenFile(const std::string &name, fspp::mode_t mode, fspp::uid_t uid, fspp::gid_t gid) override; diff --git a/src/cryfs/impl/filesystem/CryFile.h b/src/cryfs/impl/filesystem/CryFile.h index 4e66e1ca..22fdeac0 100644 --- a/src/cryfs/impl/filesystem/CryFile.h +++ b/src/cryfs/impl/filesystem/CryFile.h @@ -12,7 +12,7 @@ namespace cryfs { class CryFile final: public fspp::File, public CryNode { public: CryFile(CryDevice *device, cpputils::unique_ref parent, boost::optional> grandparent, const blockstore::BlockId &blockId); - ~CryFile(); + ~CryFile() override; cpputils::unique_ref open(fspp::openflags_t flags) override; void truncate(fspp::num_bytes_t size) override; diff --git a/src/cryfs/impl/filesystem/CryNode.cpp b/src/cryfs/impl/filesystem/CryNode.cpp index de0083ec..04db4209 100644 --- a/src/cryfs/impl/filesystem/CryNode.cpp +++ b/src/cryfs/impl/filesystem/CryNode.cpp @@ -108,7 +108,7 @@ void CryNode::rename(const bf::path &to) { if (old == boost::none) { throw FuseErrnoException(EIO); } - fsblobstore::DirEntry oldEntry = *old; // Copying this (instead of only keeping the reference) is necessary, because the operations below (i.e. RenameChild()) might make a reference invalid. + const fsblobstore::DirEntry oldEntry = *old; // Copying this (instead of only keeping the reference) is necessary, because the operations below (i.e. RenameChild()) might make a reference invalid. auto onOverwritten = [this] (const blockstore::BlockId &blockId) { device()->RemoveBlob(blockId); }; @@ -218,7 +218,7 @@ CryNode::stat_info CryNode::stat() const { result.size = fsblobstore::DirBlob::DIR_LSTAT_SIZE; //TODO If possible without performance loss, then for a directory, st_nlink should return number of dir entries (including "." and "..") result.nlink = 1; - struct timespec now = cpputils::time::now(); + const struct timespec now = cpputils::time::now(); result.atime = now; result.mtime = now; result.ctime = now; diff --git a/src/cryfs/impl/filesystem/CryNode.h b/src/cryfs/impl/filesystem/CryNode.h index c613ebb9..573e6e40 100644 --- a/src/cryfs/impl/filesystem/CryNode.h +++ b/src/cryfs/impl/filesystem/CryNode.h @@ -12,7 +12,7 @@ namespace cryfs { class CryNode: public fspp::Node { public: - virtual ~CryNode(); + ~CryNode() override; // TODO grandparent is only needed to set the timestamps of the parent directory on rename and remove. Delete grandparent parameter once we store timestamps in the blob itself instead of in the directory listing. CryNode(CryDevice *device, boost::optional> parent, boost::optional> grandparent, const blockstore::BlockId &blockId); diff --git a/src/cryfs/impl/filesystem/CryOpenFile.h b/src/cryfs/impl/filesystem/CryOpenFile.h index 58f777ab..d2b6e3d3 100644 --- a/src/cryfs/impl/filesystem/CryOpenFile.h +++ b/src/cryfs/impl/filesystem/CryOpenFile.h @@ -12,7 +12,7 @@ class CryDevice; class CryOpenFile final: public fspp::OpenFile { public: explicit CryOpenFile(const CryDevice *device, std::shared_ptr parent, cpputils::unique_ref fileBlob); - ~CryOpenFile(); + ~CryOpenFile() override; stat_info stat() const override; void truncate(fspp::num_bytes_t size) const override; diff --git a/src/cryfs/impl/filesystem/CrySymlink.h b/src/cryfs/impl/filesystem/CrySymlink.h index ed8acea5..bc8ba965 100644 --- a/src/cryfs/impl/filesystem/CrySymlink.h +++ b/src/cryfs/impl/filesystem/CrySymlink.h @@ -12,7 +12,7 @@ namespace cryfs { class CrySymlink final: public fspp::Symlink, public CryNode { public: CrySymlink(CryDevice *device, cpputils::unique_ref parent, boost::optional> grandparent, const blockstore::BlockId &blockId); - ~CrySymlink(); + ~CrySymlink() override; boost::filesystem::path target() override; diff --git a/src/cryfs/impl/filesystem/cachingfsblobstore/CachingFsBlobStore.h b/src/cryfs/impl/filesystem/cachingfsblobstore/CachingFsBlobStore.h index a4607eb4..7f53c6af 100644 --- a/src/cryfs/impl/filesystem/cachingfsblobstore/CachingFsBlobStore.h +++ b/src/cryfs/impl/filesystem/cachingfsblobstore/CachingFsBlobStore.h @@ -92,7 +92,7 @@ namespace cryfs { } inline void CachingFsBlobStore::releaseForCache(cpputils::unique_ref baseBlob) { - blockstore::BlockId blockId = baseBlob->blockId(); + const blockstore::BlockId blockId = baseBlob->blockId(); _cache.push(blockId, std::move(baseBlob)); } diff --git a/src/cryfs/impl/filesystem/fsblobstore/DirBlob.cpp b/src/cryfs/impl/filesystem/fsblobstore/DirBlob.cpp index 9639700f..c6d2478f 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/DirBlob.cpp +++ b/src/cryfs/impl/filesystem/fsblobstore/DirBlob.cpp @@ -32,12 +32,12 @@ DirBlob::DirBlob(unique_ref blob) : } DirBlob::~DirBlob() { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _writeEntriesToBlob(); } void DirBlob::flush() { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _writeEntriesToBlob(); baseBlob().flush(); } @@ -63,17 +63,17 @@ void DirBlob::_readEntriesFromBlob() { } void DirBlob::AddChildDir(const std::string &name, const BlockId &blobId, fspp::mode_t mode, fspp::uid_t uid, fspp::gid_t gid, timespec lastAccessTime, timespec lastModificationTime) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _addChild(name, blobId, fspp::Dir::EntryType::DIR, mode, uid, gid, lastAccessTime, lastModificationTime); } void DirBlob::AddChildFile(const std::string &name, const BlockId &blobId, fspp::mode_t mode, fspp::uid_t uid, fspp::gid_t gid, timespec lastAccessTime, timespec lastModificationTime) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _addChild(name, blobId, fspp::Dir::EntryType::FILE, mode, uid, gid, lastAccessTime, lastModificationTime); } void DirBlob::AddChildSymlink(const std::string &name, const blockstore::BlockId &blobId, fspp::uid_t uid, fspp::gid_t gid, timespec lastAccessTime, timespec lastModificationTime) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); auto mode = fspp::mode_t().addSymlinkFlag() .addUserReadFlag().addUserWriteFlag().addUserExecFlag() .addGroupReadFlag().addGroupWriteFlag().addGroupExecFlag() @@ -90,41 +90,41 @@ void DirBlob::_addChild(const std::string &name, const BlockId &blobId, void DirBlob::AddOrOverwriteChild(const std::string &name, const BlockId &blobId, fspp::Dir::EntryType entryType, fspp::mode_t mode, fspp::uid_t uid, fspp::gid_t gid, timespec lastAccessTime, timespec lastModificationTime, std::function onOverwritten) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _entries.addOrOverwrite(name, blobId, entryType, mode, uid, gid, lastAccessTime, lastModificationTime, onOverwritten); _changed = true; } void DirBlob::RenameChild(const blockstore::BlockId &blockId, const std::string &newName, std::function onOverwritten) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _entries.rename(blockId, newName, onOverwritten); _changed = true; } boost::optional DirBlob::GetChild(const string &name) const { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); return _entries.get(name); } boost::optional DirBlob::GetChild(const BlockId &blockId) const { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); return _entries.get(blockId); } void DirBlob::RemoveChild(const string &name) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _entries.remove(name); _changed = true; } void DirBlob::RemoveChild(const BlockId &blockId) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _entries.remove(blockId); _changed = true; } void DirBlob::AppendChildrenTo(vector *result) const { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); result->reserve(result->size() + _entries.size()); for (const auto &entry : _entries) { result->emplace_back(entry.type(), entry.name()); @@ -136,39 +136,39 @@ fspp::num_bytes_t DirBlob::lstat_size() const { } void DirBlob::updateAccessTimestampForChild(const BlockId &blockId, fspp::TimestampUpdateBehavior timestampUpdateBehavior) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); if (_entries.updateAccessTimestampForChild(blockId, timestampUpdateBehavior)) { _changed = true; } } void DirBlob::updateModificationTimestampForChild(const BlockId &blockId) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _entries.updateModificationTimestampForChild(blockId); _changed = true; } void DirBlob::chmodChild(const BlockId &blockId, fspp::mode_t mode) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _entries.setMode(blockId, mode); _changed = true; } void DirBlob::chownChild(const BlockId &blockId, fspp::uid_t uid, fspp::gid_t gid) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); if(_entries.setUidGid(blockId, uid, gid)) { _changed = true; } } void DirBlob::utimensChild(const BlockId &blockId, timespec lastAccessTime, timespec lastModificationTime) { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _entries.setAccessTimes(blockId, lastAccessTime, lastModificationTime); _changed = true; } cpputils::unique_ref DirBlob::releaseBaseBlob() { - std::unique_lock lock(_entriesAndChangedMutex); + const std::unique_lock lock(_entriesAndChangedMutex); _writeEntriesToBlob(); return FsBlob::releaseBaseBlob(); } diff --git a/src/cryfs/impl/filesystem/fsblobstore/DirBlob.h b/src/cryfs/impl/filesystem/fsblobstore/DirBlob.h index 684e14c4..dd50e7cc 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/DirBlob.h +++ b/src/cryfs/impl/filesystem/fsblobstore/DirBlob.h @@ -23,7 +23,7 @@ namespace cryfs { DirBlob(cpputils::unique_ref blob); - ~DirBlob(); + ~DirBlob() override; void AppendChildrenTo(std::vector *result) const; diff --git a/src/cryfs/impl/filesystem/fsblobstore/FileBlob.cpp b/src/cryfs/impl/filesystem/fsblobstore/FileBlob.cpp index 339abb60..8452dd9f 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/FileBlob.cpp +++ b/src/cryfs/impl/filesystem/fsblobstore/FileBlob.cpp @@ -22,7 +22,7 @@ unique_ref FileBlob::InitializeEmptyFile(unique_ref blob, const } fspp::num_bytes_t FileBlob::read(void *target, fspp::num_bytes_t offset, fspp::num_bytes_t count) const { - return fspp::num_bytes_t(baseBlob().tryRead(target, offset.value(), count.value())); + return fspp::num_bytes_t(static_cast(baseBlob().tryRead(target, offset.value(), count.value()))); } void FileBlob::write(const void *source, fspp::num_bytes_t offset, fspp::num_bytes_t count) { @@ -42,7 +42,7 @@ fspp::num_bytes_t FileBlob::lstat_size() const { } fspp::num_bytes_t FileBlob::size() const { - return fspp::num_bytes_t(baseBlob().size()); + return fspp::num_bytes_t(static_cast(baseBlob().size())); } } diff --git a/src/cryfs/impl/filesystem/fsblobstore/FsBlobStore.cpp b/src/cryfs/impl/filesystem/fsblobstore/FsBlobStore.cpp index 6e0d0707..a3144756 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/FsBlobStore.cpp +++ b/src/cryfs/impl/filesystem/fsblobstore/FsBlobStore.cpp @@ -22,7 +22,7 @@ boost::optional> FsBlobStore::load(const blockstore::BlockId if (blob == none) { return none; } - FsBlobView::BlobType blobType = FsBlobView::blobType(**blob); + const FsBlobView::BlobType blobType = FsBlobView::blobType(**blob); if (blobType == FsBlobView::BlobType::FILE) { return unique_ref(make_unique_ref(std::move(*blob))); } else if (blobType == FsBlobView::BlobType::DIR) { @@ -60,7 +60,7 @@ boost::optional> FsBlobStore::load(const blockstore::BlockId FsBlobView::migrate(node.get(), parentId); perBlobCallback(node->numNodes()); if (FsBlobView::blobType(*node) == FsBlobView::BlobType::DIR) { - DirBlob dir(std::move(node)); + const DirBlob dir(std::move(node)); vector children; dir.AppendChildrenTo(&children); for (const auto &child : children) { diff --git a/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.cpp b/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.cpp index c1f7e57d..7a99ba05 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.cpp +++ b/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.cpp @@ -1,6 +1,5 @@ #include "FsBlobView.h" -using cpputils::Data; namespace cryfs { constexpr uint16_t FsBlobView::FORMAT_VERSION_HEADER; diff --git a/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.h b/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.h index 0a0a720b..5a433f27 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.h +++ b/src/cryfs/impl/filesystem/fsblobstore/FsBlobView.h @@ -109,7 +109,7 @@ namespace cryfs { static constexpr unsigned int HEADER_SIZE = sizeof(FORMAT_VERSION_HEADER) + sizeof(uint8_t) + blockstore::BlockId::BINARY_LENGTH; static void _checkHeader(const blobstore::Blob &blob) { - uint16_t actualFormatVersion = getFormatVersionHeader(blob); + const uint16_t actualFormatVersion = getFormatVersionHeader(blob); if (FORMAT_VERSION_HEADER != actualFormatVersion) { throw std::runtime_error("This file system entity has the wrong format. Was it created with a newer version of CryFS?"); } diff --git a/src/cryfs/impl/filesystem/fsblobstore/SymlinkBlob.cpp b/src/cryfs/impl/filesystem/fsblobstore/SymlinkBlob.cpp index 67f14af2..7fe057d2 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/SymlinkBlob.cpp +++ b/src/cryfs/impl/filesystem/fsblobstore/SymlinkBlob.cpp @@ -21,7 +21,7 @@ SymlinkBlob::SymlinkBlob(unique_ref blob) unique_ref SymlinkBlob::InitializeSymlink(unique_ref blob, const bf::path &target, const blockstore::BlockId &parent) { InitializeBlob(blob.get(), FsBlobView::BlobType::SYMLINK, parent); FsBlobView symlinkBlobView(std::move(blob)); - string targetStr = target.string(); + const string targetStr = target.string(); symlinkBlobView.resize(targetStr.size()); symlinkBlobView.write(targetStr.c_str(), 0, targetStr.size()); return make_unique_ref(symlinkBlobView.releaseBaseBlob()); @@ -40,7 +40,7 @@ const bf::path &SymlinkBlob::target() const { } fspp::num_bytes_t SymlinkBlob::lstat_size() const { - return fspp::num_bytes_t(target().string().size()); + return fspp::num_bytes_t(static_cast(target().string().size())); } } diff --git a/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntry.cpp b/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntry.cpp index 70dd5a56..7731758e 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntry.cpp +++ b/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntry.cpp @@ -37,7 +37,7 @@ namespace cryfs { timespec deserializeTimeValue_(const char **pos) { timespec value{}; - value.tv_sec = deserialize_(pos); + value.tv_sec = static_cast(deserialize_(pos)); value.tv_nsec = deserialize_(pos); return value; } @@ -48,7 +48,7 @@ namespace cryfs { } string deserializeString_(const char **pos) { - size_t length = strlen(*pos); + const size_t length = strlen(*pos); string value(*pos, length); *pos += length + 1; return value; @@ -88,15 +88,15 @@ namespace cryfs { } const char *DirEntry::deserializeAndAddToVector(const char *pos, vector *result) { - fspp::Dir::EntryType type = static_cast(deserialize_(&pos)); - fspp::mode_t mode = fspp::mode_t(deserialize_(&pos)); - fspp::uid_t uid = fspp::uid_t(deserialize_(&pos)); - fspp::gid_t gid = fspp::gid_t(deserialize_(&pos)); - timespec lastAccessTime = deserializeTimeValue_(&pos); - timespec lastModificationTime = deserializeTimeValue_(&pos); - timespec lastMetadataChangeTime = deserializeTimeValue_(&pos); - string name = deserializeString_(&pos); - BlockId blockId = deserializeBlockId_(&pos); + const fspp::Dir::EntryType type = static_cast(deserialize_(&pos)); + const fspp::mode_t mode = fspp::mode_t(deserialize_(&pos)); + const fspp::uid_t uid = fspp::uid_t(deserialize_(&pos)); + const fspp::gid_t gid = fspp::gid_t(deserialize_(&pos)); + const timespec lastAccessTime = deserializeTimeValue_(&pos); + const timespec lastModificationTime = deserializeTimeValue_(&pos); + const timespec lastMetadataChangeTime = deserializeTimeValue_(&pos); + const string name = deserializeString_(&pos); + const BlockId blockId = deserializeBlockId_(&pos); result->emplace_back(type, name, blockId, mode, uid, gid, lastAccessTime, lastModificationTime, lastMetadataChangeTime); return pos; diff --git a/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntryList.cpp b/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntryList.cpp index 8f8edc02..699621d7 100644 --- a/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntryList.cpp +++ b/src/cryfs/impl/filesystem/fsblobstore/utils/DirEntryList.cpp @@ -182,7 +182,7 @@ vector::iterator DirEntryList::_findFirst(const BlockId &hint, std::fu if (_entries.size() == 0) { return _entries.end(); } - double startpos_percent = static_cast(*static_cast(hint.data().data())) / std::numeric_limits::max(); + const double startpos_percent = static_cast(*static_cast(hint.data().data())) / std::numeric_limits::max(); auto iter = _entries.begin() + static_cast(startpos_percent * static_cast(_entries.size()-1)); ASSERT(iter >= _entries.begin() && iter < _entries.end(), "Startpos out of range"); while(iter != _entries.begin() && pred(*iter)) { diff --git a/src/cryfs/impl/filesystem/parallelaccessfsblobstore/FsBlobRef.h b/src/cryfs/impl/filesystem/parallelaccessfsblobstore/FsBlobRef.h index a66ade62..42936532 100644 --- a/src/cryfs/impl/filesystem/parallelaccessfsblobstore/FsBlobRef.h +++ b/src/cryfs/impl/filesystem/parallelaccessfsblobstore/FsBlobRef.h @@ -10,7 +10,7 @@ namespace parallelaccessfsblobstore { class FsBlobRef: public parallelaccessstore::ParallelAccessStore::ResourceRefBase { public: - virtual ~FsBlobRef() {} + ~FsBlobRef() override {} virtual const blockstore::BlockId &blockId() const = 0; virtual fspp::num_bytes_t lstat_size() const = 0; virtual const blockstore::BlockId &parentPointer() const = 0; diff --git a/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.cpp b/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.cpp index 226d7e6c..d059ecde 100644 --- a/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.cpp +++ b/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.cpp @@ -31,7 +31,7 @@ optional> ParallelAccessFsBlobStore::load(const BlockId &b unique_ref ParallelAccessFsBlobStore::createDirBlob(const blockstore::BlockId &parent) { auto blob = _baseBlobStore->createDirBlob(parent); - BlockId blockId = blob->blockId(); + const BlockId blockId = blob->blockId(); return _parallelAccessStore.add(blockId, std::move(blob), [] (cachingfsblobstore::FsBlobRef *resource) { auto dirBlob = dynamic_cast(resource); ASSERT(dirBlob != nullptr, "Wrong resource given"); @@ -41,7 +41,7 @@ unique_ref ParallelAccessFsBlobStore::createDirBlob(const blockstore unique_ref ParallelAccessFsBlobStore::createFileBlob(const blockstore::BlockId &parent) { auto blob = _baseBlobStore->createFileBlob(parent); - BlockId blockId = blob->blockId(); + const BlockId blockId = blob->blockId(); return _parallelAccessStore.add(blockId, std::move(blob), [] (cachingfsblobstore::FsBlobRef *resource) { auto fileBlob = dynamic_cast(resource); ASSERT(fileBlob != nullptr, "Wrong resource given"); @@ -51,7 +51,7 @@ unique_ref ParallelAccessFsBlobStore::createFileBlob(const blocksto unique_ref ParallelAccessFsBlobStore::createSymlinkBlob(const bf::path &target, const blockstore::BlockId &parent) { auto blob = _baseBlobStore->createSymlinkBlob(target, parent); - BlockId blockId = blob->blockId(); + const BlockId blockId = blob->blockId(); return _parallelAccessStore.add(blockId, std::move(blob), [] (cachingfsblobstore::FsBlobRef *resource) { auto symlinkBlob = dynamic_cast(resource); ASSERT(symlinkBlob != nullptr, "Wrong resource given"); diff --git a/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.h b/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.h index 5ea1202f..17693770 100644 --- a/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.h +++ b/src/cryfs/impl/filesystem/parallelaccessfsblobstore/ParallelAccessFsBlobStore.h @@ -46,7 +46,7 @@ namespace cryfs { } inline void ParallelAccessFsBlobStore::remove(cpputils::unique_ref blob) { - blockstore::BlockId blockId = blob->blockId(); + const blockstore::BlockId blockId = blob->blockId(); return _parallelAccessStore.remove(blockId, std::move(blob)); } diff --git a/src/cryfs/impl/localstate/BasedirMetadata.cpp b/src/cryfs/impl/localstate/BasedirMetadata.cpp index d32ced93..769de2ea 100644 --- a/src/cryfs/impl/localstate/BasedirMetadata.cpp +++ b/src/cryfs/impl/localstate/BasedirMetadata.cpp @@ -10,7 +10,6 @@ namespace bf = boost::filesystem; using boost::property_tree::ptree; using boost::property_tree::write_json; using boost::property_tree::read_json; -using boost::none; using std::ostream; using std::istream; using std::ifstream; diff --git a/src/cryfs/impl/localstate/LocalStateDir.cpp b/src/cryfs/impl/localstate/LocalStateDir.cpp index 8803ce84..810991df 100644 --- a/src/cryfs/impl/localstate/LocalStateDir.cpp +++ b/src/cryfs/impl/localstate/LocalStateDir.cpp @@ -8,9 +8,9 @@ namespace cryfs { bf::path LocalStateDir::forFilesystemId(const CryConfig::FilesystemID &filesystemId) const { _createDirIfNotExists(_appDir); - bf::path filesystems_dir = _appDir / "filesystems"; + const bf::path filesystems_dir = _appDir / "filesystems"; _createDirIfNotExists(filesystems_dir); - bf::path this_filesystem_dir = filesystems_dir / filesystemId.ToString(); + const bf::path this_filesystem_dir = filesystems_dir / filesystemId.ToString(); _createDirIfNotExists(this_filesystem_dir); return this_filesystem_dir; } diff --git a/src/cryfs/impl/localstate/LocalStateMetadata.cpp b/src/cryfs/impl/localstate/LocalStateMetadata.cpp index 31643ad7..3a15f42c 100644 --- a/src/cryfs/impl/localstate/LocalStateMetadata.cpp +++ b/src/cryfs/impl/localstate/LocalStateMetadata.cpp @@ -111,9 +111,9 @@ LocalStateMetadata LocalStateMetadata::deserialize_(istream& stream) { ptree pt; read_json(stream, pt); - uint32_t myClientId = pt.get("myClientId"); - string encryptionKeySalt = pt.get("encryptionKey.salt"); - string encryptionKeyDigest = pt.get("encryptionKey.hash"); + const uint32_t myClientId = pt.get("myClientId"); + const string encryptionKeySalt = pt.get("encryptionKey.salt"); + const string encryptionKeyDigest = pt.get("encryptionKey.hash"); return LocalStateMetadata(myClientId, Hash{ /*.digest = */ cpputils::hash::Digest::FromString(encryptionKeyDigest), diff --git a/src/fspp/fs_interface/Context.h b/src/fspp/fs_interface/Context.h index 0e5d786c..10f46341 100644 --- a/src/fspp/fs_interface/Context.h +++ b/src/fspp/fs_interface/Context.h @@ -2,15 +2,17 @@ #ifndef MESSMER_FSPP_FSINTERFACE_CONTEXT_H_ #define MESSMER_FSPP_FSINTERFACE_CONTEXT_H_ +#include +#include #include #include -#include namespace fspp { namespace detail { class TimestampUpdateBehaviorBase { public: + virtual ~TimestampUpdateBehaviorBase() = default; virtual bool shouldUpdateATimeOnFileRead(timespec oldATime, timespec oldMTime, timespec newATime) const = 0; virtual bool shouldUpdateATimeOnDirectoryRead(timespec oldATime, timespec oldMTime, timespec newATime) const = 0; }; @@ -32,7 +34,7 @@ inline TimestampUpdateBehavior noatime() { } }; - static std::shared_ptr singleton = std::make_shared(); + static const std::shared_ptr singleton = std::make_shared(); return singleton; } @@ -48,7 +50,7 @@ inline TimestampUpdateBehavior strictatime() { } }; - static std::shared_ptr singleton = std::make_shared(); + static const std::shared_ptr singleton = std::make_shared(); return singleton; } @@ -70,7 +72,7 @@ inline TimestampUpdateBehavior relatime() { } }; - static std::shared_ptr singleton = std::make_shared(); + static const std::shared_ptr singleton = std::make_shared(); return singleton; } @@ -86,7 +88,7 @@ inline TimestampUpdateBehavior nodiratime_relatime() { } }; - static std::shared_ptr singleton = std::make_shared(); + static const std::shared_ptr singleton = std::make_shared(); return singleton; } @@ -102,7 +104,7 @@ inline TimestampUpdateBehavior nodiratime_strictatime() { } }; - static std::shared_ptr singleton = std::make_shared(); + static const std::shared_ptr singleton = std::make_shared(); return singleton; } diff --git a/src/fspp/fstest/FsppDeviceTest_Timestamps.h b/src/fspp/fstest/FsppDeviceTest_Timestamps.h index a6adbd7a..cf958bc0 100644 --- a/src/fspp/fstest/FsppDeviceTest_Timestamps.h +++ b/src/fspp/fstest/FsppDeviceTest_Timestamps.h @@ -33,7 +33,7 @@ public: auto node = this->device->Load("/mynode"); //Test that timestamps didn't change - fspp::Node::stat_info newStat = this->stat(*node.value()); + const fspp::Node::stat_info newStat = this->stat(*node.value()); EXPECT_EQ(oldStat.atime, newStat.atime); EXPECT_EQ(oldStat.mtime, newStat.mtime); EXPECT_EQ(oldStat.ctime, newStat.ctime); diff --git a/src/fspp/fstest/FsppDirTest_Timestamps.h b/src/fspp/fstest/FsppDirTest_Timestamps.h index c53a7f23..11910540 100644 --- a/src/fspp/fstest/FsppDirTest_Timestamps.h +++ b/src/fspp/fstest/FsppDirTest_Timestamps.h @@ -38,9 +38,9 @@ TYPED_TEST_P(FsppDirTest_Timestamps, createAndOpenFile_inRootDir) { TYPED_TEST_P(FsppDirTest_Timestamps, createAndOpenFile_TimestampsOfCreatedFile) { this->testBuilder().withAnyAtimeConfig([&] { auto dir = this->CreateDir("/mydir"); - timespec lowerBound = cpputils::time::now(); + const timespec lowerBound = cpputils::time::now(); dir->createAndOpenFile("childname", fspp::mode_t().addFileFlag(), fspp::uid_t(1000), fspp::gid_t(1000)); - timespec upperBound = cpputils::time::now(); + const timespec upperBound = cpputils::time::now(); auto child = this->Load("/mydir/childname"); this->EXPECT_ACCESS_TIMESTAMP_BETWEEN (lowerBound, upperBound, *child); this->EXPECT_MODIFICATION_TIMESTAMP_BETWEEN (lowerBound, upperBound, *child); @@ -77,9 +77,9 @@ TYPED_TEST_P(FsppDirTest_Timestamps, createDir_inRootDir) { TYPED_TEST_P(FsppDirTest_Timestamps, createDir_TimestampsOfCreatedDir) { this->testBuilder().withAnyAtimeConfig([&] { auto dir = this->CreateDir("/mydir"); - timespec lowerBound = cpputils::time::now(); + const timespec lowerBound = cpputils::time::now(); dir->createDir("childname", fspp::mode_t().addDirFlag(), fspp::uid_t(1000), fspp::gid_t(1000)); - timespec upperBound = cpputils::time::now(); + const timespec upperBound = cpputils::time::now(); auto child = this->Load("/mydir/childname"); this->EXPECT_ACCESS_TIMESTAMP_BETWEEN (lowerBound, upperBound, *child); this->EXPECT_MODIFICATION_TIMESTAMP_BETWEEN (lowerBound, upperBound, *child); @@ -116,9 +116,9 @@ TYPED_TEST_P(FsppDirTest_Timestamps, createSymlink_inRootDir) { TYPED_TEST_P(FsppDirTest_Timestamps, createSymlink_TimestampsOfCreatedSymlink) { this->testBuilder().withAnyAtimeConfig([&] { auto dir = this->CreateDir("/mydir"); - timespec lowerBound = cpputils::time::now(); + const timespec lowerBound = cpputils::time::now(); dir->createSymlink("childname", "/target", fspp::uid_t(1000), fspp::gid_t(1000)); - timespec upperBound = cpputils::time::now(); + const timespec upperBound = cpputils::time::now(); auto child = this->Load("/mydir/childname"); this->EXPECT_ACCESS_TIMESTAMP_BETWEEN (lowerBound, upperBound, *child); this->EXPECT_MODIFICATION_TIMESTAMP_BETWEEN (lowerBound, upperBound, *child); diff --git a/src/fspp/fstest/FsppFileTest.h b/src/fspp/fstest/FsppFileTest.h index 8785c70d..989037c7 100644 --- a/src/fspp/fstest/FsppFileTest.h +++ b/src/fspp/fstest/FsppFileTest.h @@ -4,6 +4,8 @@ #include +#include + #include "testutils/FileTest.h" //TODO Restructure. FsppFileTest tests fspp::File interface. All tests for fspp::Node interface go to a FsppNodeTest. diff --git a/src/fspp/fstest/FsppNodeTest_Timestamps.h b/src/fspp/fstest/FsppNodeTest_Timestamps.h index c08d174b..ac35db84 100644 --- a/src/fspp/fstest/FsppNodeTest_Timestamps.h +++ b/src/fspp/fstest/FsppNodeTest_Timestamps.h @@ -14,9 +14,9 @@ public: void Test_Create() { this->testBuilder().withAnyAtimeConfig([&] { - timespec lowerBound = cpputils::time::now(); + const timespec lowerBound = cpputils::time::now(); auto node = this->CreateNode("/mynode"); - timespec upperBound = cpputils::time::now(); + const timespec upperBound = cpputils::time::now(); this->EXPECT_ACCESS_TIMESTAMP_BETWEEN(lowerBound, upperBound, *node); this->EXPECT_MODIFICATION_TIMESTAMP_BETWEEN(lowerBound, upperBound, *node); this->EXPECT_METADATACHANGE_TIMESTAMP_BETWEEN(lowerBound, upperBound, *node); @@ -38,7 +38,7 @@ public: void Test_Chmod() { auto operation = [this] { auto node = this->CreateNode("/mynode"); - fspp::mode_t mode = this->stat(*node).mode; + const fspp::mode_t mode = this->stat(*node).mode; return [mode, node = std::move(node)] { node->chmod(mode); }; @@ -51,8 +51,8 @@ public: void Test_Chown() { auto operation = [this] { auto node = this->CreateNode("/mynode"); - fspp::uid_t uid = this->stat(*node).uid; - fspp::gid_t gid = this->stat(*node).gid; + const fspp::uid_t uid = this->stat(*node).uid; + const fspp::gid_t gid = this->stat(*node).gid; return [uid, gid, node = std::move(node)] { node->chown(uid, gid); }; @@ -357,8 +357,8 @@ public: void Test_Utimens() { this->testBuilder().withAnyAtimeConfig([&] { auto node = this->CreateNode("/mynode"); - timespec atime = this->xSecondsAgo(100); - timespec mtime = this->xSecondsAgo(200); + const timespec atime = this->xSecondsAgo(100); + const timespec mtime = this->xSecondsAgo(200); auto operation = [atime, mtime, &node] { node->utimens(atime, mtime); }; diff --git a/src/fspp/fstest/FsppOpenFileTest.h b/src/fspp/fstest/FsppOpenFileTest.h index 98950421..af15fe04 100644 --- a/src/fspp/fstest/FsppOpenFileTest.h +++ b/src/fspp/fstest/FsppOpenFileTest.h @@ -23,7 +23,7 @@ public: void EXPECT_NUMBYTES_READABLE(fspp::num_bytes_t expectedSize, fspp::OpenFile *openFile) { cpputils::Data data(expectedSize.value()); //Try to read one byte more than the expected size - fspp::num_bytes_t readBytes = openFile->read(data.data(), expectedSize+fspp::num_bytes_t(1), fspp::num_bytes_t(0)); + const fspp::num_bytes_t readBytes = openFile->read(data.data(), expectedSize+fspp::num_bytes_t(1), fspp::num_bytes_t(0)); //and check that it only read the expected size (but also not less) EXPECT_EQ(expectedSize, readBytes); } diff --git a/src/fspp/fstest/testutils/FileSystemTest.h b/src/fspp/fstest/testutils/FileSystemTest.h index 81b7599e..5edd26d6 100644 --- a/src/fspp/fstest/testutils/FileSystemTest.h +++ b/src/fspp/fstest/testutils/FileSystemTest.h @@ -2,12 +2,13 @@ #ifndef MESSMER_FSPP_FSTEST_TESTUTILS_FILESYSTEMTEST_H_ #define MESSMER_FSPP_FSTEST_TESTUTILS_FILESYSTEMTEST_H_ -#include -#include #include #include #include #include +#include +#include +#include #include "../../fs_interface/Device.h" #include "../../fs_interface/Node.h" diff --git a/src/fspp/fstest/testutils/FileTest.h b/src/fspp/fstest/testutils/FileTest.h index 1e758ab2..c72354a1 100644 --- a/src/fspp/fstest/testutils/FileTest.h +++ b/src/fspp/fstest/testutils/FileTest.h @@ -11,16 +11,18 @@ template class FileTest: public FileSystemTest { public: FileTest(): file_root(), file_nested() { - this->LoadDir("/")->createAndOpenFile("myfile", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); - file_root = this->LoadFile("/myfile"); - file_root_node = this->Load("/myfile"); + // NOLINTBEGIN(cppcoreguidelines-prefer-member-initializer) + this->LoadDir("/")->createAndOpenFile("myfile", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); + file_root = this->LoadFile("/myfile"); + file_root_node = this->Load("/myfile"); - this->LoadDir("/")->createDir("mydir", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); - this->LoadDir("/mydir")->createAndOpenFile("mynestedfile", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); - file_nested = this->LoadFile("/mydir/mynestedfile"); - file_nested_node = this->Load("/mydir/mynestedfile"); + this->LoadDir("/")->createDir("mydir", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); + this->LoadDir("/mydir")->createAndOpenFile("mynestedfile", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); + file_nested = this->LoadFile("/mydir/mynestedfile"); + file_nested_node = this->Load("/mydir/mynestedfile"); - this->LoadDir("/")->createDir("mydir2", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); + this->LoadDir("/")->createDir("mydir2", this->MODE_PUBLIC, fspp::uid_t(0), fspp::gid_t(0)); + // NOLINTEND(cppcoreguidelines-prefer-member-initializer) } std::unique_ptr file_root; std::unique_ptr file_nested; @@ -36,20 +38,20 @@ public: } void EXPECT_SIZE(fspp::num_bytes_t expectedSize, fspp::File *file, fspp::Node *node) { - IN_STAT(file, node, [expectedSize] (const fspp::Node::stat_info& st) { - EXPECT_EQ(expectedSize, st.size); - }); + IN_STAT(file, node, [expectedSize] (const fspp::Node::stat_info& st) { + EXPECT_EQ(expectedSize, st.size); + }); - EXPECT_NUMBYTES_READABLE(expectedSize, file); + EXPECT_NUMBYTES_READABLE(expectedSize, file); } void EXPECT_NUMBYTES_READABLE(fspp::num_bytes_t expectedSize, fspp::File *file) { - auto openFile = file->open(fspp::openflags_t::RDONLY()); - cpputils::Data data(expectedSize.value()); - //Try to read one byte more than the expected size - fspp::num_bytes_t readBytes = openFile->read(data.data(), expectedSize+fspp::num_bytes_t(1), fspp::num_bytes_t(0)); - //and check that it only read the expected size (but also not less) - EXPECT_EQ(expectedSize, readBytes); + auto openFile = file->open(fspp::openflags_t::RDONLY()); + cpputils::Data data(expectedSize.value()); + //Try to read one byte more than the expected size + const fspp::num_bytes_t readBytes = openFile->read(data.data(), expectedSize+fspp::num_bytes_t(1), fspp::num_bytes_t(0)); + //and check that it only read the expected size (but also not less) + EXPECT_EQ(expectedSize, readBytes); } void EXPECT_ATIME_EQ(struct timespec expected, const fspp::Node::stat_info& st) { @@ -58,8 +60,8 @@ public: } void EXPECT_MTIME_EQ(struct timespec expected, const fspp::Node::stat_info& st) { - EXPECT_EQ(expected.tv_sec, st.mtime.tv_sec); - EXPECT_EQ(expected.tv_nsec, st.mtime.tv_nsec); + EXPECT_EQ(expected.tv_sec, st.mtime.tv_sec); + EXPECT_EQ(expected.tv_nsec, st.mtime.tv_nsec); } }; diff --git a/src/fspp/fstest/testutils/TimestampTestUtils.h b/src/fspp/fstest/testutils/TimestampTestUtils.h index 82d46b34..0cfc2266 100644 --- a/src/fspp/fstest/testutils/TimestampTestUtils.h +++ b/src/fspp/fstest/testutils/TimestampTestUtils.h @@ -28,9 +28,9 @@ public: void EXPECT_OPERATION_UPDATES_TIMESTAMPS_AS(std::function statOld, std::function statNew, Operation&& operation, std::initializer_list behaviorChecks) { auto oldStat = statOld(); ensureNodeTimestampsAreOld(oldStat); - timespec timeBeforeOperation = cpputils::time::now(); + const timespec timeBeforeOperation = cpputils::time::now(); operation(); - timespec timeAfterOperation = cpputils::time::now(); + const timespec timeAfterOperation = cpputils::time::now(); auto newStat = statNew(); for (auto behaviorCheck : behaviorChecks) { behaviorCheck(oldStat, newStat, timeBeforeOperation, timeAfterOperation); diff --git a/src/fspp/fuse/Fuse.cpp b/src/fspp/fuse/Fuse.cpp index 4b881815..21327595 100644 --- a/src/fspp/fuse/Fuse.cpp +++ b/src/fspp/fuse/Fuse.cpp @@ -50,7 +50,7 @@ bool is_valid_fspp_path(const bf::path& path) { class ThreadNameForDebugging final { public: ThreadNameForDebugging(const string& threadName) { - std::string name = "fspp_" + threadName; + const std::string name = "fspp_" + threadName; set_thread_name(name.c_str()); } @@ -67,7 +67,7 @@ public: namespace { int fusepp_getattr(const char *path, fspp::fuse::STAT *stbuf) { - int rs = FUSE_OBJ->getattr(bf::path(path), stbuf); + const int rs = FUSE_OBJ->getattr(bf::path(path), stbuf); return rs; } @@ -316,7 +316,7 @@ void extractAllAtimeOptionsAndRemoveOnesUnknownToLibfuse_(string* csv_options, v | ranges::views::filter( [&] (auto&& elem_) { // TODO string_view would be better - std::string elem(&*elem_.begin(), ranges::distance(elem_)); + const std::string elem(&*elem_.begin(), ranges::distance(elem_)); if (is_fuse_unsupported_atime_flag(elem)) { result->push_back(elem); return false; @@ -359,7 +359,7 @@ void Fuse::_run(const bf::path &mountdir, vector fuseOptions) { ASSERT(_argv.size() == 0, "Filesystem already started"); - vector atimeOptions = extractAllAtimeOptionsAndRemoveOnesUnknownToLibfuse_(&fuseOptions); + const vector atimeOptions = extractAllAtimeOptionsAndRemoveOnesUnknownToLibfuse_(&fuseOptions); _createContext(atimeOptions); _argv = _build_argv(mountdir, fuseOptions); @@ -489,8 +489,8 @@ void Fuse::unmount(const bf::path& mountdir, bool force) { BOOL success = DokanRemoveMountPoint(mountdir_.c_str()); int returncode = success ? 0 : -1; #else - std::vector args = force ? std::vector({"-u", mountdir.string()}) : std::vector({"-u", "-z", mountdir.string()}); // "-z" takes care that if the filesystem can't be unmounted right now because something is opened, it will be unmounted as soon as it can be. - int returncode = cpputils::Subprocess::call("fusermount", args, "").exitcode; + const std::vector args = force ? std::vector({"-u", mountdir.string()}) : std::vector({"-u", "-z", mountdir.string()}); // "-z" takes care that if the filesystem can't be unmounted right now because something is opened, it will be unmounted as soon as it can be. + const int returncode = cpputils::Subprocess::call("fusermount", args, "").exitcode; #endif if (returncode != 0) { throw std::runtime_error("Could not unmount filesystem"); @@ -498,7 +498,7 @@ void Fuse::unmount(const bf::path& mountdir, bool force) { } int Fuse::getattr(const bf::path &path, fspp::fuse::STAT *stbuf) { - ThreadNameForDebugging _threadName("getattr"); + const ThreadNameForDebugging _threadName("getattr"); #ifdef FSPP_LOG LOG(DEBUG, "getattr({}, _, _)", path); #endif @@ -527,7 +527,7 @@ int Fuse::getattr(const bf::path &path, fspp::fuse::STAT *stbuf) { } int Fuse::fgetattr(const bf::path &path, fspp::fuse::STAT *stbuf, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("fgetattr"); + const ThreadNameForDebugging _threadName("fgetattr"); #ifdef FSPP_LOG LOG(DEBUG, "fgetattr({}, _, _)", path); #endif @@ -538,7 +538,7 @@ int Fuse::fgetattr(const bf::path &path, fspp::fuse::STAT *stbuf, fuse_file_info // underlying base directory instead of doing the fgetattr(). // TODO Check if necessary if (path.string() == "/") { - int result = getattr(path, stbuf); + const int result = getattr(path, stbuf); #ifdef FSPP_LOG LOG(DEBUG, "fgetattr({}, _, _): success", path); #endif @@ -570,7 +570,7 @@ int Fuse::fgetattr(const bf::path &path, fspp::fuse::STAT *stbuf, fuse_file_info } int Fuse::readlink(const bf::path &path, char *buf, size_t size) { - ThreadNameForDebugging _threadName("readlink"); + const ThreadNameForDebugging _threadName("readlink"); #ifdef FSPP_LOG LOG(DEBUG, "readlink({}, _, {})", path, size); #endif @@ -602,13 +602,13 @@ int Fuse::mknod(const bf::path &path, ::mode_t mode, dev_t rdev) { UNUSED(rdev); UNUSED(mode); UNUSED(path); - ThreadNameForDebugging _threadName("mknod"); + const ThreadNameForDebugging _threadName("mknod"); LOG(WARN, "Called non-implemented mknod({}, {}, _)", path.string(), mode); return ENOSYS; } int Fuse::mkdir(const bf::path &path, ::mode_t mode) { - ThreadNameForDebugging _threadName("mkdir"); + const ThreadNameForDebugging _threadName("mkdir"); #ifdef FSPP_LOG LOG(DEBUG, "mkdir({}, {})", path.string(), mode); #endif @@ -646,7 +646,7 @@ int Fuse::mkdir(const bf::path &path, ::mode_t mode) { } int Fuse::unlink(const bf::path &path) { - ThreadNameForDebugging _threadName("unlink"); + const ThreadNameForDebugging _threadName("unlink"); #ifdef FSPP_LOG LOG(DEBUG, "unlink({})", path); #endif @@ -675,7 +675,7 @@ int Fuse::unlink(const bf::path &path) { } int Fuse::rmdir(const bf::path &path) { - ThreadNameForDebugging _threadName("rmdir"); + const ThreadNameForDebugging _threadName("rmdir"); #ifdef FSPP_LOG LOG(DEBUG, "rmdir({})", path); #endif @@ -704,7 +704,7 @@ int Fuse::rmdir(const bf::path &path) { } int Fuse::symlink(const bf::path &to, const bf::path &from) { - ThreadNameForDebugging _threadName("symlink"); + const ThreadNameForDebugging _threadName("symlink"); #ifdef FSPP_LOG LOG(DEBUG, "symlink({}, {})", to, from); #endif @@ -734,7 +734,7 @@ int Fuse::symlink(const bf::path &to, const bf::path &from) { } int Fuse::rename(const bf::path &from, const bf::path &to) { - ThreadNameForDebugging _threadName("rename"); + const ThreadNameForDebugging _threadName("rename"); #ifdef FSPP_LOG LOG(DEBUG, "rename({}, {})", from, to); #endif @@ -765,7 +765,7 @@ int Fuse::rename(const bf::path &from, const bf::path &to) { //TODO int Fuse::link(const bf::path &from, const bf::path &to) { - ThreadNameForDebugging _threadName("link"); + const ThreadNameForDebugging _threadName("link"); LOG(WARN, "NOT IMPLEMENTED: link({}, {})", from.string(), to.string()); //auto real_from = _impl->RootDir() / from; //auto real_to = _impl->RootDir() / to; @@ -775,7 +775,7 @@ int Fuse::link(const bf::path &from, const bf::path &to) { } int Fuse::chmod(const bf::path &path, ::mode_t mode) { - ThreadNameForDebugging _threadName("chmod"); + const ThreadNameForDebugging _threadName("chmod"); #ifdef FSPP_LOG LOG(DEBUG, "chmod({}, {})", path, mode); #endif @@ -804,7 +804,7 @@ int Fuse::chmod(const bf::path &path, ::mode_t mode) { } int Fuse::chown(const bf::path &path, ::uid_t uid, ::gid_t gid) { - ThreadNameForDebugging _threadName("chown"); + const ThreadNameForDebugging _threadName("chown"); #ifdef FSPP_LOG LOG(DEBUG, "chown({}, {}, {})", path, uid, gid); #endif @@ -833,7 +833,7 @@ int Fuse::chown(const bf::path &path, ::uid_t uid, ::gid_t gid) { } int Fuse::truncate(const bf::path &path, int64_t size) { - ThreadNameForDebugging _threadName("truncate"); + const ThreadNameForDebugging _threadName("truncate"); #ifdef FSPP_LOG LOG(DEBUG, "truncate({}, {})", path, size); #endif @@ -862,7 +862,7 @@ int Fuse::truncate(const bf::path &path, int64_t size) { } int Fuse::ftruncate(const bf::path &path, int64_t size, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("ftruncate"); + const ThreadNameForDebugging _threadName("ftruncate"); #ifdef FSPP_LOG LOG(DEBUG, "ftruncate({}, {})", path, size); #endif @@ -891,7 +891,7 @@ int Fuse::ftruncate(const bf::path &path, int64_t size, fuse_file_info *fileinfo } int Fuse::utimens(const bf::path &path, const std::array times) { - ThreadNameForDebugging _threadName("utimens"); + const ThreadNameForDebugging _threadName("utimens"); #ifdef FSPP_LOG LOG(DEBUG, "utimens({}, _)", path); #endif @@ -920,7 +920,7 @@ int Fuse::utimens(const bf::path &path, const std::array times) { } int Fuse::open(const bf::path &path, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("open"); + const ThreadNameForDebugging _threadName("open"); #ifdef FSPP_LOG LOG(DEBUG, "open({}, _)", path); #endif @@ -949,7 +949,7 @@ int Fuse::open(const bf::path &path, fuse_file_info *fileinfo) { } int Fuse::release(const bf::path &path, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("release"); + const ThreadNameForDebugging _threadName("release"); #ifdef FSPP_LOG LOG(DEBUG, "release({}, _)", path); #endif @@ -978,13 +978,13 @@ int Fuse::release(const bf::path &path, fuse_file_info *fileinfo) { } int Fuse::read(const bf::path &path, char *buf, size_t size, int64_t offset, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("read"); + const ThreadNameForDebugging _threadName("read"); #ifdef FSPP_LOG LOG(DEBUG, "read({}, _, {}, {}, _)", path, size, offset); #endif UNUSED(path); try { - int result = _fs->read(fileinfo->fh, buf, fspp::num_bytes_t(size), fspp::num_bytes_t(offset)).value(); + const int result = _fs->read(fileinfo->fh, buf, fspp::num_bytes_t(size), fspp::num_bytes_t(offset)).value(); #ifdef FSPP_LOG LOG(DEBUG, "read({}, _, {}, {}, _): success with {}", path, size, offset, result); #endif @@ -1007,7 +1007,7 @@ int Fuse::read(const bf::path &path, char *buf, size_t size, int64_t offset, fus } int Fuse::write(const bf::path &path, const char *buf, size_t size, int64_t offset, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("write"); + const ThreadNameForDebugging _threadName("write"); #ifdef FSPP_LOG LOG(DEBUG, "write({}, _, {}, {}, _)", path, size, offset); #endif @@ -1036,7 +1036,7 @@ int Fuse::write(const bf::path &path, const char *buf, size_t size, int64_t offs } int Fuse::statfs(const bf::path &path, struct ::statvfs *fsstat) { - ThreadNameForDebugging _threadName("statfs"); + const ThreadNameForDebugging _threadName("statfs"); #ifdef FSPP_LOG LOG(DEBUG, "statfs({}, _)", path); #endif @@ -1066,7 +1066,7 @@ int Fuse::statfs(const bf::path &path, struct ::statvfs *fsstat) { } int Fuse::flush(const bf::path &path, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("flush"); + const ThreadNameForDebugging _threadName("flush"); #ifdef FSPP_LOG LOG(WARN, "flush({}, _)", path); #endif @@ -1095,7 +1095,7 @@ int Fuse::flush(const bf::path &path, fuse_file_info *fileinfo) { } int Fuse::fsync(const bf::path &path, int datasync, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("fsync"); + const ThreadNameForDebugging _threadName("fsync"); #ifdef FSPP_LOG LOG(DEBUG, "fsync({}, {}, _)", path, datasync); #endif @@ -1130,14 +1130,14 @@ int Fuse::fsync(const bf::path &path, int datasync, fuse_file_info *fileinfo) { int Fuse::opendir(const bf::path &path, fuse_file_info *fileinfo) { UNUSED(path); UNUSED(fileinfo); - ThreadNameForDebugging _threadName("opendir"); + const ThreadNameForDebugging _threadName("opendir"); //LOG(DEBUG, "opendir({}, _)", path); //We don't need opendir, because readdir works directly on the path return 0; } int Fuse::readdir(const bf::path &path, void *buf, fuse_fill_dir_t filler, int64_t offset, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("readdir"); + const ThreadNameForDebugging _threadName("readdir"); #ifdef FSPP_LOG LOG(DEBUG, "readdir({}, _, _, {}, _)", path, offset); #endif @@ -1192,7 +1192,7 @@ int Fuse::readdir(const bf::path &path, void *buf, fuse_fill_dir_t filler, int64 int Fuse::releasedir(const bf::path &path, fuse_file_info *fileinfo) { UNUSED(path); UNUSED(fileinfo); - ThreadNameForDebugging _threadName("releasedir"); + const ThreadNameForDebugging _threadName("releasedir"); //LOG(DEBUG, "releasedir({}, _)", path); //We don't need releasedir, because readdir works directly on the path return 0; @@ -1203,14 +1203,14 @@ int Fuse::fsyncdir(const bf::path &path, int datasync, fuse_file_info *fileinfo) UNUSED(fileinfo); UNUSED(datasync); UNUSED(path); - ThreadNameForDebugging _threadName("fsyncdir"); + const ThreadNameForDebugging _threadName("fsyncdir"); //LOG(WARN, "Called non-implemented fsyncdir({}, {}, _)", path, datasync); return 0; } void Fuse::init(fuse_conn_info *conn) { UNUSED(conn); - ThreadNameForDebugging _threadName("init"); + const ThreadNameForDebugging _threadName("init"); _fs = _init(this); ASSERT(_context != boost::none, "Context should have been initialized in Fuse::run() but somehow didn't"); @@ -1227,7 +1227,7 @@ void Fuse::init(fuse_conn_info *conn) { } void Fuse::destroy() { - ThreadNameForDebugging _threadName("destroy"); + const ThreadNameForDebugging _threadName("destroy"); _fs = make_shared(); LOG(INFO, "Filesystem stopped."); _running = false; @@ -1235,7 +1235,7 @@ void Fuse::destroy() { } int Fuse::access(const bf::path &path, int mask) { - ThreadNameForDebugging _threadName("access"); + const ThreadNameForDebugging _threadName("access"); #ifdef FSPP_LOG LOG(DEBUG, "access({}, {})", path, mask); #endif @@ -1264,7 +1264,7 @@ int Fuse::access(const bf::path &path, int mask) { } int Fuse::create(const bf::path &path, ::mode_t mode, fuse_file_info *fileinfo) { - ThreadNameForDebugging _threadName("create"); + const ThreadNameForDebugging _threadName("create"); #ifdef FSPP_LOG LOG(DEBUG, "create({}, {}, _)", path, mode); #endif diff --git a/src/fspp/impl/FilesystemImpl.cpp b/src/fspp/impl/FilesystemImpl.cpp index 1497c3ea..b7ec6a3a 100644 --- a/src/fspp/impl/FilesystemImpl.cpp +++ b/src/fspp/impl/FilesystemImpl.cpp @@ -313,7 +313,7 @@ void FilesystemImpl::utimens(const bf::path &path, timespec lastAccessTime, time void FilesystemImpl::statfs(struct ::statvfs *fsstat) { PROFILE(_statfsNanosec); - Device::statvfs stat = _device->statfs(); + const Device::statvfs stat = _device->statfs(); fsstat->f_bsize = stat.blocksize; fsstat->f_blocks = stat.num_total_blocks; @@ -337,7 +337,7 @@ void FilesystemImpl::createSymlink(const bf::path &to, const bf::path &from, ::u void FilesystemImpl::readSymlink(const bf::path &path, char *buf, fspp::num_bytes_t size) { PROFILE(_readSymlinkNanosec); - string target = LoadSymlink(path)->target().string(); + const string target = LoadSymlink(path)->target().string(); PROFILE(_readSymlinkNanosec_withoutLoading); std::memcpy(buf, target.c_str(), std::min(static_cast(target.size()+1), size.value())); buf[size.value()-1] = '\0'; diff --git a/src/fspp/impl/FilesystemImpl.h b/src/fspp/impl/FilesystemImpl.h index 9ff43f24..3e7d40ee 100644 --- a/src/fspp/impl/FilesystemImpl.h +++ b/src/fspp/impl/FilesystemImpl.h @@ -22,7 +22,7 @@ class OpenFile; class FilesystemImpl final: public fuse::Filesystem { public: explicit FilesystemImpl(cpputils::unique_ref device); - virtual ~FilesystemImpl(); + ~FilesystemImpl() override; void setContext(Context&& context) override; diff --git a/src/fspp/impl/FuseOpenFileList.h b/src/fspp/impl/FuseOpenFileList.h index 795a6fb5..a47abeb4 100644 --- a/src/fspp/impl/FuseOpenFileList.h +++ b/src/fspp/impl/FuseOpenFileList.h @@ -71,9 +71,9 @@ inline FuseOpenFileList::~FuseOpenFileList() { } inline int FuseOpenFileList::open(cpputils::unique_ref file) { - std::lock_guard lock(_mutex); + const std::lock_guard lock(_mutex); - int descriptor = _open_files.add(std::move(file)); + const int descriptor = _open_files.add(std::move(file)); _refcounts.emplace(descriptor, 0); return descriptor; } @@ -83,7 +83,7 @@ inline auto FuseOpenFileList::load(int descriptor, Func&& callback) { try { std::unique_lock lock(_mutex); _refcounts.at(descriptor) += 1; - detail::OnScopeExit _([&] { + const detail::OnScopeExit _([&] { if (!lock.owns_lock()) { // own_lock can be true when _open_files.get() below fails before the lock is unlocked lock.lock(); } diff --git a/src/fspp/impl/IdList.h b/src/fspp/impl/IdList.h index c0b9a16b..a1fae953 100644 --- a/src/fspp/impl/IdList.h +++ b/src/fspp/impl/IdList.h @@ -40,7 +40,7 @@ IdList::~IdList() { template int IdList::add(cpputils::unique_ref entry) { //TODO Reuse IDs (ids = descriptors) - int new_id = ++_id_counter; + const int new_id = ++_id_counter; _entries.emplace(new_id, std::move(entry)); return new_id; } diff --git a/src/fspp/impl/Profiler.h b/src/fspp/impl/Profiler.h index 66282714..6886989a 100644 --- a/src/fspp/impl/Profiler.h +++ b/src/fspp/impl/Profiler.h @@ -24,7 +24,7 @@ namespace fspp { } inline Profiler::~Profiler() { - uint64_t timeDiff = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - _beginTime).count(); + const uint64_t timeDiff = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - _beginTime).count(); *_targetForAddingNanosec += timeDiff; } } diff --git a/src/gitversion/VersionCompare.cpp b/src/gitversion/VersionCompare.cpp index fc410c03..cc53b6f3 100644 --- a/src/gitversion/VersionCompare.cpp +++ b/src/gitversion/VersionCompare.cpp @@ -8,15 +8,15 @@ using std::string; namespace gitversion { bool VersionCompare::isOlderThan(const string &v1Str, const string &v2Str) { - VersionInfo v1 = Parser::parse(v1Str); - VersionInfo v2 = Parser::parse(v2Str); - unsigned long v1_major = std::stoul(v1.majorVersion); - unsigned long v2_major = std::stoul(v2.majorVersion); - unsigned long v1_minor = std::stoul(v1.minorVersion); - unsigned long v2_minor = std::stoul(v2.minorVersion); - unsigned long v1_hotfix = std::stoul(v1.hotfixVersion); - unsigned long v2_hotfix = std::stoul(v2.hotfixVersion); - int versionTagCompare = _versionTagCompare(v1.versionTag, v2.versionTag); + const VersionInfo v1 = Parser::parse(v1Str); + const VersionInfo v2 = Parser::parse(v2Str); + const unsigned long v1_major = std::stoul(v1.majorVersion); + const unsigned long v2_major = std::stoul(v2.majorVersion); + const unsigned long v1_minor = std::stoul(v1.minorVersion); + const unsigned long v2_minor = std::stoul(v2.minorVersion); + const unsigned long v1_hotfix = std::stoul(v1.hotfixVersion); + const unsigned long v2_hotfix = std::stoul(v2.hotfixVersion); + const int versionTagCompare = _versionTagCompare(v1.versionTag, v2.versionTag); return (v1_major < v2_major) || ((v1_major == v2_major) && ( (v1_minor < v2_minor) || ((v1_minor == v2_minor) && ( (v1_hotfix < v2_hotfix) || ((v1_hotfix == v2_hotfix) && ( diff --git a/src/gitversion/gitversion.cpp b/src/gitversion/gitversion.cpp index f6966f04..f562947b 100644 --- a/src/gitversion/gitversion.cpp +++ b/src/gitversion/gitversion.cpp @@ -6,7 +6,7 @@ using std::string; namespace gitversion { const VersionInfo &parse() { - static VersionInfo versionInfo = Parser::parse(VersionString()); + static const VersionInfo versionInfo = Parser::parse(VersionString()); return versionInfo; } diff --git a/src/parallelaccessstore/ParallelAccessStore.h b/src/parallelaccessstore/ParallelAccessStore.h index 296e643c..c2d15afe 100644 --- a/src/parallelaccessstore/ParallelAccessStore.h +++ b/src/parallelaccessstore/ParallelAccessStore.h @@ -117,7 +117,7 @@ ParallelAccessStore::ParallelAccessStore(cpputils::u template bool ParallelAccessStore::isOpened(const Key &key) const { - std::lock_guard lock(_mutex); + const std::lock_guard lock(_mutex); return _openResources.find(key) != _openResources.end(); }; @@ -132,7 +132,7 @@ template template cpputils::unique_ref ParallelAccessStore::add(const Key &key, cpputils::unique_ref resource, std::function(Resource*)> createResourceRef) { static_assert(std::is_base_of::value, "Wrong ResourceRef type"); - std::lock_guard lock(_mutex); + const std::lock_guard lock(_mutex); return _add(key, std::move(resource), createResourceRef); } @@ -156,7 +156,7 @@ cpputils::unique_ref ParallelAccessStore cpputils::unique_ref ParallelAccessStore::loadOrAdd(const Key &key, std::function onExists, std::function ()> onAdd, std::function(Resource*)> createResourceRef) { - std::lock_guard lock(_mutex); + const std::lock_guard lock(_mutex); auto found = _openResources.find(key); if (found == _openResources.end()) { auto resource = onAdd(); @@ -179,7 +179,7 @@ boost::optional> ParallelAccessStore boost::optional> ParallelAccessStore::load(const Key &key, std::function(Resource*)> createResourceRef) { //TODO This lock doesn't allow loading different blocks in parallel. Can we only lock the requested key? - std::lock_guard lock(_mutex); + const std::lock_guard lock(_mutex); auto found = _openResources.find(key); if (found == _openResources.end()) { auto resource = _baseStore->loadFromBaseStore(key); @@ -202,14 +202,14 @@ void ParallelAccessStore::remove(const Key &key, cpp //Wait for last resource user to release it auto resourceToRemove = resourceToRemoveFuture.get(); - std::lock_guard lock(_mutex); // TODO Just added this as a precaution on a whim, but I seriously need to rethink locking here. + const std::lock_guard lock(_mutex); // TODO Just added this as a precaution on a whim, but I seriously need to rethink locking here. _resourcesToRemove.erase(key); //TODO Is this erase causing a race condition? _baseStore->removeFromBaseStore(std::move(resourceToRemove)); } template boost::future> ParallelAccessStore::_resourceToRemoveFuture(const Key &key) { - std::lock_guard lock(_mutex); // TODO Lock needed for _resourcesToRemove? + const std::lock_guard lock(_mutex); // TODO Lock needed for _resourcesToRemove? auto insertResult = _resourcesToRemove.emplace(key, boost::promise>()); ASSERT(true == insertResult.second, "Inserting failed"); return insertResult.first->second.get_future(); @@ -222,7 +222,7 @@ void ParallelAccessStore::remove(const Key &key) { auto resourceToRemoveFuture = _resourceToRemoveFuture(key); //Wait for last resource user to release it auto resourceToRemove = resourceToRemoveFuture.get(); - std::lock_guard lock(_mutex); // TODO Just added this as a precaution on a whim, but I seriously need to rethink locking here. + const std::lock_guard lock(_mutex); // TODO Just added this as a precaution on a whim, but I seriously need to rethink locking here. _resourcesToRemove.erase(key); //TODO Is this erase causing a race condition? _baseStore->removeFromBaseStore(std::move(resourceToRemove)); } else { @@ -232,7 +232,7 @@ void ParallelAccessStore::remove(const Key &key) { template void ParallelAccessStore::release(const Key &key) { - std::lock_guard lock(_mutex); + const std::lock_guard lock(_mutex); auto found = _openResources.find(key); ASSERT(found != _openResources.end(), "Didn't find key"); found->second.releaseReference(); diff --git a/src/stats/main.cpp b/src/stats/main.cpp index 5535c959..669e5574 100644 --- a/src/stats/main.cpp +++ b/src/stats/main.cpp @@ -106,7 +106,7 @@ std::vector getKnownBlobIds(const path& basedir, const CryConfigLoader: auto blockStore = makeBlockStore(basedir, config, localStateDir); auto fsBlobStore = make_unique_ref(make_unique_ref(std::move(blockStore), config.configFile->config()->BlocksizeBytes())); - std::vector result; + const std::vector result; AccumulateBlockIds knownBlobIds; cout << "Listing all file system entities (i.e. blobs)..." << flush; auto rootId = BlockId::FromString(config.configFile->config()->RootBlob()); @@ -176,7 +176,7 @@ int main(int argc, char* argv[]) { std::cerr << "Usage: cryfs-stats [basedir]" << std::endl; exit(1); } - path basedir = argv[1]; + const path basedir = argv[1]; std::cout << "Calculating stats for filesystem at " << basedir << std::endl; auto console = std::make_shared(); @@ -222,7 +222,7 @@ int main(int argc, char* argv[]) { set unaccountedBlocks = getAllBlockIds(basedir, config.right(), localStateDir); cout << "done" << endl; - vector accountedBlocks = getKnownBlockIds(basedir, config.right(), localStateDir); + const vector accountedBlocks = getKnownBlockIds(basedir, config.right(), localStateDir); for (const BlockId& blockId : accountedBlocks) { auto num_erased = unaccountedBlocks.erase(blockId); ASSERT(1 == num_erased, "Blob id referenced by directory entry but didn't found it on disk? This can't happen."); @@ -233,7 +233,7 @@ int main(int argc, char* argv[]) { auto blockStore = makeBlockStore(basedir, config.right(), localStateDir); auto nodeStore = make_unique_ref(std::move(blockStore), config.right().configFile->config()->BlocksizeBytes()); - uint32_t numUnaccountedBlocks = unaccountedBlocks.size(); + const uint32_t numUnaccountedBlocks = unaccountedBlocks.size(); uint32_t numLeaves = 0; uint32_t numInner = 0; console->print("Unaccounted blocks: " + std::to_string(unaccountedBlocks.size()) + "\n"); diff --git a/test/blobstore/implementations/onblocks/BigBlobsTest.cpp b/test/blobstore/implementations/onblocks/BigBlobsTest.cpp index f65dedc2..0043b6b8 100644 --- a/test/blobstore/implementations/onblocks/BigBlobsTest.cpp +++ b/test/blobstore/implementations/onblocks/BigBlobsTest.cpp @@ -5,8 +5,10 @@ #include #include #include -#include "blobstore/implementations/onblocks/BlobStoreOnBlocks.h" + #include "blobstore/implementations/onblocks/BlobOnBlocks.h" +#include "blobstore/implementations/onblocks/BlobStoreOnBlocks.h" +#include using namespace blobstore; using namespace blobstore::onblocks; diff --git a/test/blobstore/implementations/onblocks/BlobReadWriteTest.cpp b/test/blobstore/implementations/onblocks/BlobReadWriteTest.cpp index 4a6bba48..26175b64 100644 --- a/test/blobstore/implementations/onblocks/BlobReadWriteTest.cpp +++ b/test/blobstore/implementations/onblocks/BlobReadWriteTest.cpp @@ -67,13 +67,13 @@ TEST_F(BlobReadWriteTest, WritingCloseTo16ByteLimitDoesntDestroySize) { TEST_F(BlobReadWriteTest, givenEmptyBlob_whenTryReadInFirstLeaf_thenFails) { Data data(5); - size_t read = blob->tryRead(data.data(), 3, 5); + const size_t read = blob->tryRead(data.data(), 3, 5); EXPECT_EQ(0, read); } TEST_F(BlobReadWriteTest, givenEmptyBlob_whenTryReadInLaterLeaf_thenFails) { Data data(5); - size_t read = blob->tryRead(data.data(), 2*LAYOUT.maxBytesPerLeaf(), 5); + const size_t read = blob->tryRead(data.data(), 2*LAYOUT.maxBytesPerLeaf(), 5); EXPECT_EQ(0, read); } @@ -92,7 +92,7 @@ TEST_F(BlobReadWriteTest, givenEmptyBlob_whenReadInLaterLeaf_thenFails) { } TEST_F(BlobReadWriteTest, givenEmptyBlob_whenReadAll_thenReturnsZeroSizedData) { - Data data = blob->readAll(); + const Data data = blob->readAll(); EXPECT_EQ(0, data.size()); } @@ -110,13 +110,13 @@ TEST_F(BlobReadWriteTest, givenEmptyBlob_whenWriteZeroBytes_thenDoesntGrow) { TEST_F(BlobReadWriteTest, givenBlobResizedToZero_whenTryReadInFirstLeaf_thenFails) { Data data(5); - size_t read = blob->tryRead(data.data(), 3, 5); + const size_t read = blob->tryRead(data.data(), 3, 5); EXPECT_EQ(0, read); } TEST_F(BlobReadWriteTest, givenBlobResizedToZero_whenTryReadInLaterLeaf_thenFails) { Data data(5); - size_t read = blob->tryRead(data.data(), 2*LAYOUT.maxBytesPerLeaf(), 5); + const size_t read = blob->tryRead(data.data(), 2*LAYOUT.maxBytesPerLeaf(), 5); EXPECT_EQ(0, read); } @@ -135,7 +135,7 @@ TEST_F(BlobReadWriteTest, givenBlobResizedToZero_whenReadInLaterLeaf_thenFails) } TEST_F(BlobReadWriteTest, givenBlobResizedToZero_whenReadAll_thenReturnsZeroSizedData) { - Data data = blob->readAll(); + const Data data = blob->readAll(); EXPECT_EQ(0, data.size()); } diff --git a/test/blobstore/implementations/onblocks/BlobSizeTest.cpp b/test/blobstore/implementations/onblocks/BlobSizeTest.cpp index 5e063e5b..6f0d1c5b 100644 --- a/test/blobstore/implementations/onblocks/BlobSizeTest.cpp +++ b/test/blobstore/implementations/onblocks/BlobSizeTest.cpp @@ -64,7 +64,7 @@ TEST_F(BlobSizeTest, ResizingToItself_Large) { } TEST_F(BlobSizeTest, EmptyBlobStaysEmptyWhenLoading) { - BlockId blockId = blob->blockId(); + const BlockId blockId = blob->blockId(); reset(std::move(blob)); auto loaded = loadBlob(blockId); EXPECT_EQ(0u, loaded->size()); @@ -72,7 +72,7 @@ TEST_F(BlobSizeTest, EmptyBlobStaysEmptyWhenLoading) { TEST_F(BlobSizeTest, BlobSizeStaysIntactWhenLoading) { blob->resize(LARGE_SIZE); - BlockId blockId = blob->blockId(); + const BlockId blockId = blob->blockId(); reset(std::move(blob)); auto loaded = loadBlob(blockId); EXPECT_EQ(LARGE_SIZE, loaded->size()); diff --git a/test/blobstore/implementations/onblocks/BlobStoreTest.cpp b/test/blobstore/implementations/onblocks/BlobStoreTest.cpp index aab75fc1..238bf7a2 100644 --- a/test/blobstore/implementations/onblocks/BlobStoreTest.cpp +++ b/test/blobstore/implementations/onblocks/BlobStoreTest.cpp @@ -23,7 +23,7 @@ TEST_F(BlobStoreTest, TwoCreatedBlobsHaveDifferentKeys) { TEST_F(BlobStoreTest, BlobIsNotLoadableAfterDeletion_DeleteDirectly) { auto blob = blobStore->create(); - BlockId blockId = blob->blockId(); + const BlockId blockId = blob->blockId(); blobStore->remove(std::move(blob)); EXPECT_FALSE(static_cast(blobStore->load(blockId))); } @@ -36,7 +36,7 @@ TEST_F(BlobStoreTest, BlobIsNotLoadableAfterDeletion_DeleteByKey) { TEST_F(BlobStoreTest, BlobIsNotLoadableAfterDeletion_DeleteAfterLoading) { auto blob = blobStore->create(); - BlockId blockId = blob->blockId(); + const BlockId blockId = blob->blockId(); reset(std::move(blob)); blobStore->remove(loadBlob(blockId)); EXPECT_FALSE(static_cast(blobStore->load(blockId))); diff --git a/test/blobstore/implementations/onblocks/datanodestore/DataInnerNodeTest.cpp b/test/blobstore/implementations/onblocks/datanodestore/DataInnerNodeTest.cpp index 6cb7b86c..dd23060b 100644 --- a/test/blobstore/implementations/onblocks/datanodestore/DataInnerNodeTest.cpp +++ b/test/blobstore/implementations/onblocks/datanodestore/DataInnerNodeTest.cpp @@ -114,7 +114,7 @@ private: constexpr uint32_t DataInnerNodeTest::BLOCKSIZE_BYTES; TEST_F(DataInnerNodeTest, CorrectKeyReturnedAfterLoading) { - BlockId blockId = DataInnerNode::CreateNewNode(blockStore, nodeStore->layout(), 1, {leaf->blockId()})->blockId(); + const BlockId blockId = DataInnerNode::CreateNewNode(blockStore, nodeStore->layout(), 1, {leaf->blockId()})->blockId(); auto loaded = nodeStore->load(blockId).value(); EXPECT_EQ(blockId, loaded->blockId()); @@ -143,7 +143,7 @@ TEST_F(DataInnerNodeTest, IsCorrectlyInitializedAfterLoading) { } TEST_F(DataInnerNodeTest, AddingASecondLeaf) { - BlockId leaf2_blockId = AddALeafTo(node.get()); + const BlockId leaf2_blockId = AddALeafTo(node.get()); EXPECT_EQ(2u, node->numChildren()); EXPECT_EQ(leaf->blockId(), node->readChild(0).blockId()); @@ -179,7 +179,7 @@ TEST_F(DataInnerNodeTest, BuildingAThreeLevelTreeAndReload) { TEST_F(DataInnerNodeTest, ConvertToInternalNode) { auto child = nodeStore->createNewLeafNode(Data(0)); - BlockId node_blockId = node->blockId(); + const BlockId node_blockId = node->blockId(); unique_ref converted = DataNode::convertToNewInnerNode(std::move(node), nodeStore->layout(), *child); EXPECT_EQ(1u, converted->numChildren()); @@ -188,7 +188,7 @@ TEST_F(DataInnerNodeTest, ConvertToInternalNode) { } TEST_F(DataInnerNodeTest, ConvertToInternalNodeZeroesOutChildrenRegion) { - BlockId blockId = CreateNodeWithDataConvertItToInnerNodeAndReturnKey(); + const BlockId blockId = CreateNodeWithDataConvertItToInnerNodeAndReturnKey(); auto block = blockStore->load(blockId).value(); EXPECT_EQ(0, std::memcmp(ZEROES.data(), static_cast(block->data())+DataNodeLayout::HEADERSIZE_BYTES+sizeof(DataInnerNode::ChildEntry), nodeStore->layout().maxBytesPerLeaf()-sizeof(DataInnerNode::ChildEntry))); @@ -220,12 +220,12 @@ TEST_F(DataInnerNodeTest, LastChildWhenOneChild) { } TEST_F(DataInnerNodeTest, LastChildWhenTwoChildren) { - BlockId blockId = AddALeafTo(node.get()); + const BlockId blockId = AddALeafTo(node.get()); EXPECT_EQ(blockId, node->readLastChild().blockId()); } TEST_F(DataInnerNodeTest, LastChildWhenThreeChildren) { AddALeafTo(node.get()); - BlockId blockId = AddALeafTo(node.get()); + const BlockId blockId = AddALeafTo(node.get()); EXPECT_EQ(blockId, node->readLastChild().blockId()); } diff --git a/test/blobstore/implementations/onblocks/datanodestore/DataLeafNodeTest.cpp b/test/blobstore/implementations/onblocks/datanodestore/DataLeafNodeTest.cpp index 3c4bd21b..bf4c6d11 100644 --- a/test/blobstore/implementations/onblocks/datanodestore/DataLeafNodeTest.cpp +++ b/test/blobstore/implementations/onblocks/datanodestore/DataLeafNodeTest.cpp @@ -123,7 +123,7 @@ constexpr uint32_t DataLeafNodeTest::BLOCKSIZE_BYTES; constexpr DataNodeLayout DataLeafNodeTest::LAYOUT; TEST_F(DataLeafNodeTest, CorrectKeyReturnedAfterLoading) { - BlockId blockId = DataLeafNode::CreateNewNode(blockStore, LAYOUT, Data(LAYOUT.maxBytesPerLeaf()))->blockId(); + const BlockId blockId = DataLeafNode::CreateNewNode(blockStore, LAYOUT, Data(LAYOUT.maxBytesPerLeaf()))->blockId(); auto loaded = nodeStore->load(blockId).value(); EXPECT_EQ(blockId, loaded->blockId()); @@ -135,7 +135,7 @@ TEST_F(DataLeafNodeTest, InitializesCorrectly) { } TEST_F(DataLeafNodeTest, ReadWrittenDataAfterReloadingBlock) { - BlockId blockId = WriteDataToNewLeafBlockAndReturnKey(); + const BlockId blockId = WriteDataToNewLeafBlockAndReturnKey(); auto loaded = LoadLeafNode(blockId); @@ -148,7 +148,7 @@ TEST_F(DataLeafNodeTest, NewLeafNodeHasSizeZero) { } TEST_F(DataLeafNodeTest, NewLeafNodeHasSizeZero_AfterLoading) { - BlockId blockId = nodeStore->createNewLeafNode(Data(0))->blockId(); + const BlockId blockId = nodeStore->createNewLeafNode(Data(0))->blockId(); auto leaf = LoadLeafNode(blockId); EXPECT_EQ(0u, leaf->numBytes()); @@ -170,7 +170,7 @@ TEST_P(DataLeafNodeSizeTest, ResizeNode_ReadSizeImmediately) { } TEST_P(DataLeafNodeSizeTest, ResizeNode_ReadSizeAfterLoading) { - BlockId blockId = CreateLeafResizeItAndReturnKey(); + const BlockId blockId = CreateLeafResizeItAndReturnKey(); auto leaf = LoadLeafNode(blockId); EXPECT_EQ(GetParam(), leaf->numBytes()); @@ -184,7 +184,7 @@ TEST_F(DataLeafNodeTest, SpaceIsZeroFilledWhenGrowing) { TEST_F(DataLeafNodeTest, SpaceGetsZeroFilledWhenShrinkingAndRegrowing) { FillLeafBlockWithData(); // resize it smaller and then back to original size - uint32_t smaller_size = randomData.size() - 100; + const uint32_t smaller_size = randomData.size() - 100; leaf->resize(smaller_size); leaf->resize(randomData.size()); @@ -193,8 +193,8 @@ TEST_F(DataLeafNodeTest, SpaceGetsZeroFilledWhenShrinkingAndRegrowing) { } TEST_F(DataLeafNodeTest, DataGetsZeroFilledWhenShrinking) { - BlockId blockId = WriteDataToNewLeafBlockAndReturnKey(); - uint32_t smaller_size = randomData.size() - 100; + const BlockId blockId = WriteDataToNewLeafBlockAndReturnKey(); + const uint32_t smaller_size = randomData.size() - 100; { //At first, we expect there to be random data in the underlying data block auto block = blockStore->load(blockId).value(); @@ -211,7 +211,7 @@ TEST_F(DataLeafNodeTest, DataGetsZeroFilledWhenShrinking) { TEST_F(DataLeafNodeTest, ShrinkingDoesntDestroyValidDataRegion) { FillLeafBlockWithData(); - uint32_t smaller_size = randomData.size() - 100; + const uint32_t smaller_size = randomData.size() - 100; leaf->resize(smaller_size); //Check that the remaining data region is unchanged @@ -220,7 +220,7 @@ TEST_F(DataLeafNodeTest, ShrinkingDoesntDestroyValidDataRegion) { TEST_F(DataLeafNodeTest, ConvertToInternalNode) { auto child = nodeStore->createNewLeafNode(Data(0)); - BlockId leaf_blockId = leaf->blockId(); + const BlockId leaf_blockId = leaf->blockId(); unique_ref converted = DataNode::convertToNewInnerNode(std::move(leaf), LAYOUT, *child); EXPECT_EQ(1u, converted->numChildren()); @@ -229,7 +229,7 @@ TEST_F(DataLeafNodeTest, ConvertToInternalNode) { } TEST_F(DataLeafNodeTest, ConvertToInternalNodeZeroesOutChildrenRegion) { - BlockId blockId = CreateLeafWithDataConvertItToInnerNodeAndReturnKey(); + const BlockId blockId = CreateLeafWithDataConvertItToInnerNodeAndReturnKey(); auto block = blockStore->load(blockId).value(); EXPECT_EQ(0, std::memcmp(ZEROES.data(), static_cast(block->data())+DataNodeLayout::HEADERSIZE_BYTES+sizeof(DataInnerNode::ChildEntry), nodeStore->layout().maxBytesPerLeaf()-sizeof(DataInnerNode::ChildEntry))); @@ -327,7 +327,7 @@ TEST_P(DataLeafNodeDataTest, WriteAndReadImmediately) { } TEST_P(DataLeafNodeDataTest, WriteAndReadAfterLoading) { - BlockId blockId = CreateLeafWriteToItAndReturnKey(this->foregroundData); + const BlockId blockId = CreateLeafWriteToItAndReturnKey(this->foregroundData); auto loaded_leaf = LoadLeafNode(blockId); EXPECT_DATA_READS_AS(this->foregroundData, *loaded_leaf, GetParam().offset, GetParam().count); diff --git a/test/blobstore/implementations/onblocks/datanodestore/DataNodeStoreTest.cpp b/test/blobstore/implementations/onblocks/datanodestore/DataNodeStoreTest.cpp index da24e58b..bfe38dfb 100644 --- a/test/blobstore/implementations/onblocks/datanodestore/DataNodeStoreTest.cpp +++ b/test/blobstore/implementations/onblocks/datanodestore/DataNodeStoreTest.cpp @@ -49,7 +49,7 @@ TEST_F(DataNodeStoreTest, CreateInnerNodeCreatesInnerNode) { } TEST_F(DataNodeStoreTest, LeafNodeIsRecognizedAfterStoreAndLoad) { - BlockId blockId = nodeStore->createNewLeafNode(Data(0))->blockId(); + const BlockId blockId = nodeStore->createNewLeafNode(Data(0))->blockId(); auto loaded_node = nodeStore->load(blockId).value(); @@ -58,7 +58,7 @@ TEST_F(DataNodeStoreTest, LeafNodeIsRecognizedAfterStoreAndLoad) { TEST_F(DataNodeStoreTest, InnerNodeWithDepth1IsRecognizedAfterStoreAndLoad) { auto leaf = nodeStore->createNewLeafNode(Data(0)); - BlockId blockId = nodeStore->createNewInnerNode(1, {leaf->blockId()})->blockId(); + const BlockId blockId = nodeStore->createNewInnerNode(1, {leaf->blockId()})->blockId(); auto loaded_node = nodeStore->load(blockId).value(); @@ -68,7 +68,7 @@ TEST_F(DataNodeStoreTest, InnerNodeWithDepth1IsRecognizedAfterStoreAndLoad) { TEST_F(DataNodeStoreTest, InnerNodeWithDepth2IsRecognizedAfterStoreAndLoad) { auto leaf = nodeStore->createNewLeafNode(Data(0)); auto inner = nodeStore->createNewInnerNode(1, {leaf->blockId()}); - BlockId blockId = nodeStore->createNewInnerNode(2, {inner->blockId()})->blockId(); + const BlockId blockId = nodeStore->createNewInnerNode(2, {inner->blockId()})->blockId(); auto loaded_node = nodeStore->load(blockId).value(); @@ -77,7 +77,7 @@ TEST_F(DataNodeStoreTest, InnerNodeWithDepth2IsRecognizedAfterStoreAndLoad) { TEST_F(DataNodeStoreTest, DataNodeCrashesOnLoadIfDepthIsTooHigh) { auto block = blockStore->create(Data(BLOCKSIZE_BYTES)); - BlockId blockId = block->blockId(); + const BlockId blockId = block->blockId(); { DataNodeView view(std::move(block)); view.setDepth(DataNodeStore::MAX_DEPTH + 1); diff --git a/test/blobstore/implementations/onblocks/datanodestore/DataNodeViewTest.cpp b/test/blobstore/implementations/onblocks/datanodestore/DataNodeViewTest.cpp index d0a59656..2799aaaf 100644 --- a/test/blobstore/implementations/onblocks/datanodestore/DataNodeViewTest.cpp +++ b/test/blobstore/implementations/onblocks/datanodestore/DataNodeViewTest.cpp @@ -40,7 +40,7 @@ TEST_P(DataNodeViewDepthTest, DepthIsStored) { DataNodeView view(std::move(block)); view.setDepth(GetParam()); } - DataNodeView view(blockStore->load(blockId).value()); + const DataNodeView view(blockStore->load(blockId).value()); EXPECT_EQ(GetParam(), view.Depth()); } @@ -55,7 +55,7 @@ TEST_P(DataNodeViewSizeTest, SizeIsStored) { DataNodeView view(std::move(block)); view.setSize(GetParam()); } - DataNodeView view(blockStore->load(blockId).value()); + const DataNodeView view(blockStore->load(blockId).value()); EXPECT_EQ(GetParam(), view.Size()); } @@ -67,7 +67,7 @@ TEST_F(DataNodeViewTest, DataIsStored) { DataNodeView view(std::move(block)); view.write(randomData.data(), 0, randomData.size()); } - DataNodeView view(blockStore->load(blockId).value()); + const DataNodeView view(blockStore->load(blockId).value()); EXPECT_EQ(0, std::memcmp(view.data(), randomData.data(), randomData.size())); } @@ -81,7 +81,7 @@ TEST_F(DataNodeViewTest, HeaderAndBodyDontOverlap) { view.setSize(1000000000u); view.write(randomData.data(), 0, DATASIZE_BYTES); } - DataNodeView view(blockStore->load(blockId).value()); + const DataNodeView view(blockStore->load(blockId).value()); EXPECT_EQ(3, view.Depth()); EXPECT_EQ(1000000000u, view.Size()); EXPECT_EQ(0, std::memcmp(view.data(), randomData.data(), DATASIZE_BYTES)); @@ -90,7 +90,7 @@ TEST_F(DataNodeViewTest, HeaderAndBodyDontOverlap) { TEST_F(DataNodeViewTest, Data) { auto block = blockStore->create(Data(BLOCKSIZE_BYTES)); const uint8_t *blockBegin = static_cast(block->data()); - DataNodeView view(std::move(block)); + const DataNodeView view(std::move(block)); EXPECT_EQ(blockBegin+DataNodeLayout::HEADERSIZE_BYTES, static_cast(view.data())); } diff --git a/test/blobstore/implementations/onblocks/datatreestore/DataTreeStoreTest.cpp b/test/blobstore/implementations/onblocks/datatreestore/DataTreeStoreTest.cpp index eb279a31..6f6aeeed 100644 --- a/test/blobstore/implementations/onblocks/datatreestore/DataTreeStoreTest.cpp +++ b/test/blobstore/implementations/onblocks/datatreestore/DataTreeStoreTest.cpp @@ -14,7 +14,7 @@ class DataTreeStoreTest: public DataTreeTest { }; TEST_F(DataTreeStoreTest, CorrectKeyReturned) { - BlockId blockId = treeStore.createNewTree()->blockId(); + const BlockId blockId = treeStore.createNewTree()->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(blockId, tree->blockId()); } @@ -32,7 +32,7 @@ TEST_F(DataTreeStoreTest, NewTreeIsLeafOnly) { } TEST_F(DataTreeStoreTest, TreeIsNotLoadableAfterRemove_DeleteByTree) { - BlockId blockId = treeStore.createNewTree()->blockId(); + const BlockId blockId = treeStore.createNewTree()->blockId(); auto tree = treeStore.load(blockId); EXPECT_NE(none, tree); treeStore.remove(std::move(*tree)); @@ -40,7 +40,7 @@ TEST_F(DataTreeStoreTest, TreeIsNotLoadableAfterRemove_DeleteByTree) { } TEST_F(DataTreeStoreTest, TreeIsNotLoadableAfterRemove_DeleteByKey) { - BlockId blockId = treeStore.createNewTree()->blockId(); + const BlockId blockId = treeStore.createNewTree()->blockId(); treeStore.remove(blockId); EXPECT_EQ(none, treeStore.load(blockId)); } diff --git a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_NumStoredBytes.cpp b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_NumStoredBytes.cpp index b6537c5a..99808ad7 100644 --- a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_NumStoredBytes.cpp +++ b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_NumStoredBytes.cpp @@ -24,7 +24,7 @@ INSTANTIATE_TEST_SUITE_P(FullLastLeaf, DataTreeTest_NumStoredBytes_P, Values(sta //TODO Test numLeaves() and numNodes() also two configurations with same number of bytes but different number of leaves (last leaf has 0 bytes) TEST_P(DataTreeTest_NumStoredBytes_P, SingleLeaf) { - BlockId blockId = CreateLeafWithSize(GetParam())->blockId(); + const BlockId blockId = CreateLeafWithSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(GetParam(), tree->numBytes()); EXPECT_EQ(1, tree->numLeaves()); @@ -32,7 +32,7 @@ TEST_P(DataTreeTest_NumStoredBytes_P, SingleLeaf) { } TEST_P(DataTreeTest_NumStoredBytes_P, TwoLeafTree) { - BlockId blockId = CreateTwoLeafWithSecondLeafSize(GetParam())->blockId(); + const BlockId blockId = CreateTwoLeafWithSecondLeafSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(nodeStore->layout().maxBytesPerLeaf() + GetParam(), tree->numBytes()); EXPECT_EQ(2, tree->numLeaves()); @@ -40,7 +40,7 @@ TEST_P(DataTreeTest_NumStoredBytes_P, TwoLeafTree) { } TEST_P(DataTreeTest_NumStoredBytes_P, FullTwolevelTree) { - BlockId blockId = CreateFullTwoLevelWithLastLeafSize(GetParam())->blockId(); + const BlockId blockId = CreateFullTwoLevelWithLastLeafSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(nodeStore->layout().maxBytesPerLeaf()*(nodeStore->layout().maxChildrenPerInnerNode()-1) + GetParam(), tree->numBytes()); EXPECT_EQ(nodeStore->layout().maxChildrenPerInnerNode(), tree->numLeaves()); @@ -48,7 +48,7 @@ TEST_P(DataTreeTest_NumStoredBytes_P, FullTwolevelTree) { } TEST_P(DataTreeTest_NumStoredBytes_P, ThreeLevelTreeWithOneChild) { - BlockId blockId = CreateThreeLevelWithOneChildAndLastLeafSize(GetParam())->blockId(); + const BlockId blockId = CreateThreeLevelWithOneChildAndLastLeafSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(nodeStore->layout().maxBytesPerLeaf() + GetParam(), tree->numBytes()); EXPECT_EQ(2, tree->numLeaves()); @@ -56,7 +56,7 @@ TEST_P(DataTreeTest_NumStoredBytes_P, ThreeLevelTreeWithOneChild) { } TEST_P(DataTreeTest_NumStoredBytes_P, ThreeLevelTreeWithTwoChildren) { - BlockId blockId = CreateThreeLevelWithTwoChildrenAndLastLeafSize(GetParam())->blockId(); + const BlockId blockId = CreateThreeLevelWithTwoChildrenAndLastLeafSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(nodeStore->layout().maxBytesPerLeaf()*nodeStore->layout().maxChildrenPerInnerNode() + nodeStore->layout().maxBytesPerLeaf() + GetParam(), tree->numBytes()); EXPECT_EQ(2 + nodeStore->layout().maxChildrenPerInnerNode(), tree->numLeaves()); @@ -64,7 +64,7 @@ TEST_P(DataTreeTest_NumStoredBytes_P, ThreeLevelTreeWithTwoChildren) { } TEST_P(DataTreeTest_NumStoredBytes_P, ThreeLevelTreeWithThreeChildren) { - BlockId blockId = CreateThreeLevelWithThreeChildrenAndLastLeafSize(GetParam())->blockId(); + const BlockId blockId = CreateThreeLevelWithThreeChildrenAndLastLeafSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(2*nodeStore->layout().maxBytesPerLeaf()*nodeStore->layout().maxChildrenPerInnerNode() + nodeStore->layout().maxBytesPerLeaf() + GetParam(), tree->numBytes()); EXPECT_EQ(2 + 2*nodeStore->layout().maxChildrenPerInnerNode(), tree->numLeaves()); @@ -72,7 +72,7 @@ TEST_P(DataTreeTest_NumStoredBytes_P, ThreeLevelTreeWithThreeChildren) { } TEST_P(DataTreeTest_NumStoredBytes_P, FullThreeLevelTree) { - BlockId blockId = CreateFullThreeLevelWithLastLeafSize(GetParam())->blockId(); + const BlockId blockId = CreateFullThreeLevelWithLastLeafSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(nodeStore->layout().maxBytesPerLeaf()*nodeStore->layout().maxChildrenPerInnerNode()*(nodeStore->layout().maxChildrenPerInnerNode()-1) + nodeStore->layout().maxBytesPerLeaf()*(nodeStore->layout().maxChildrenPerInnerNode()-1) + GetParam(), tree->numBytes()); EXPECT_EQ(nodeStore->layout().maxChildrenPerInnerNode()*nodeStore->layout().maxChildrenPerInnerNode(), tree->numLeaves()); @@ -80,7 +80,7 @@ TEST_P(DataTreeTest_NumStoredBytes_P, FullThreeLevelTree) { } TEST_P(DataTreeTest_NumStoredBytes_P, FourLevelMinDataTree) { - BlockId blockId = CreateFourLevelMinDataWithLastLeafSize(GetParam())->blockId(); + const BlockId blockId = CreateFourLevelMinDataWithLastLeafSize(GetParam())->blockId(); auto tree = treeStore.load(blockId).value(); EXPECT_EQ(nodeStore->layout().maxBytesPerLeaf()*nodeStore->layout().maxChildrenPerInnerNode()*nodeStore->layout().maxChildrenPerInnerNode() + GetParam(), tree->numBytes()); EXPECT_EQ(1 + nodeStore->layout().maxChildrenPerInnerNode()*nodeStore->layout().maxChildrenPerInnerNode(), tree->numLeaves()); diff --git a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_Performance.cpp b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_Performance.cpp index c400917f..84ce6979 100644 --- a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_Performance.cpp +++ b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_Performance.cpp @@ -9,16 +9,16 @@ using cpputils::Data; class DataTreeTest_Performance: public DataTreeTest { public: void TraverseByWriting(DataTree *tree, uint64_t beginIndex, uint64_t endIndex) { - uint64_t offset = beginIndex * maxBytesPerLeaf; - uint64_t count = endIndex * maxBytesPerLeaf - offset; + const uint64_t offset = beginIndex * maxBytesPerLeaf; + const uint64_t count = endIndex * maxBytesPerLeaf - offset; Data data(count); data.FillWithZeroes(); tree->writeBytes(data.data(), offset, count); } void TraverseByReading(DataTree *tree, uint64_t beginIndex, uint64_t endIndex) { - uint64_t offset = beginIndex * maxBytesPerLeaf; - uint64_t count = endIndex * maxBytesPerLeaf - offset; + const uint64_t offset = beginIndex * maxBytesPerLeaf; + const uint64_t count = endIndex * maxBytesPerLeaf - offset; Data data(count); tree->readBytes(data.data(), offset, count); } diff --git a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeByTraversing.cpp b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeByTraversing.cpp index 26f8b9bf..121c9f68 100644 --- a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeByTraversing.cpp +++ b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeByTraversing.cpp @@ -31,7 +31,7 @@ public: static constexpr DataNodeLayout LAYOUT = DataNodeLayout(BLOCKSIZE_BYTES); unique_ref CreateTree(unique_ref root) { - BlockId blockId = root->blockId(); + const BlockId blockId = root->blockId(); cpputils::destruct(std::move(root)); return treeStore.load(blockId).value(); } @@ -111,9 +111,9 @@ public: } void GrowTree(DataTree *tree) { - uint64_t maxBytesPerLeaf = tree->maxBytesPerLeaf(); - uint64_t offset = traversalBeginIndex * maxBytesPerLeaf; - uint64_t count = newNumberOfLeaves * maxBytesPerLeaf - offset; + const uint64_t maxBytesPerLeaf = tree->maxBytesPerLeaf(); + const uint64_t offset = traversalBeginIndex * maxBytesPerLeaf; + const uint64_t count = newNumberOfLeaves * maxBytesPerLeaf - offset; Data data(count); data.FillWithZeroes(); tree->writeBytes(data.data(), offset, count); @@ -201,22 +201,22 @@ TEST_P(DataTreeTest_ResizeByTraversing_P, NumLeavesIsCorrect) { TEST_P(DataTreeTest_ResizeByTraversing_P, DepthFlagsAreCorrect) { GrowTree(tree.get()); - uint32_t depth = ceil(log(newNumberOfLeaves)/log(DataTreeTest_ResizeByTraversing::LAYOUT.maxChildrenPerInnerNode())); + const uint32_t depth = ceil(log(newNumberOfLeaves)/log(DataTreeTest_ResizeByTraversing::LAYOUT.maxChildrenPerInnerNode())); CHECK_DEPTH(depth, tree->blockId()); } TEST_P(DataTreeTest_ResizeByTraversing_P, KeyDoesntChange) { - BlockId blockId = tree->blockId(); + const BlockId blockId = tree->blockId(); tree->flush(); GrowTree(tree.get()); EXPECT_EQ(blockId, tree->blockId()); } TEST_P(DataTreeTest_ResizeByTraversing_P, DataStaysIntact) { - uint32_t oldNumberOfLeaves = std::max(UINT64_C(1), ceilDivision(tree->numBytes(), static_cast(nodeStore->layout().maxBytesPerLeaf()))); + const uint32_t oldNumberOfLeaves = std::max(UINT64_C(1), ceilDivision(tree->numBytes(), static_cast(nodeStore->layout().maxBytesPerLeaf()))); TwoLevelDataFixture data(nodeStore, TwoLevelDataFixture::SizePolicy::Unchanged); - BlockId blockId = tree->blockId(); + const BlockId blockId = tree->blockId(); cpputils::destruct(std::move(tree)); data.FillInto(nodeStore->load(blockId).get().get()); diff --git a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeNumBytes.cpp b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeNumBytes.cpp index a3d4e763..5d9f7637 100644 --- a/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeNumBytes.cpp +++ b/test/blobstore/implementations/onblocks/datatreestore/DataTreeTest_ResizeNumBytes.cpp @@ -31,7 +31,7 @@ public: static constexpr DataNodeLayout LAYOUT = DataNodeLayout(BLOCKSIZE_BYTES); unique_ref CreateTree(unique_ref root) { - BlockId blockId = root->blockId(); + const BlockId blockId = root->blockId(); cpputils::destruct(std::move(root)); return treeStore.load(blockId).value(); } @@ -199,21 +199,21 @@ TEST_P(DataTreeTest_ResizeNumBytes_P, NumLeavesIsCorrect_FromCache) { TEST_P(DataTreeTest_ResizeNumBytes_P, DepthFlagsAreCorrect) { tree->resizeNumBytes(newSize); tree->flush(); - uint32_t depth = ceil(log(newNumberOfLeaves)/log(DataTreeTest_ResizeNumBytes::LAYOUT.maxChildrenPerInnerNode()) - 0.00000000001); // The subtraction takes care of double inaccuracies if newNumberOfLeaves == maxChildrenPerInnerNode - CHECK_DEPTH(depth, tree->blockId()); + const uint32_t depth = ceil(log(newNumberOfLeaves)/log(DataTreeTest_ResizeNumBytes::LAYOUT.maxChildrenPerInnerNode()) - 0.00000000001); // The subtraction takes care of double inaccuracies if newNumberOfLeaves == maxChildrenPerInnerNode + CHECK_DEPTH(static_cast(depth), tree->blockId()); } TEST_P(DataTreeTest_ResizeNumBytes_P, KeyDoesntChange) { - BlockId blockId = tree->blockId(); + const BlockId blockId = tree->blockId(); tree->flush(); tree->resizeNumBytes(newSize); EXPECT_EQ(blockId, tree->blockId()); } TEST_P(DataTreeTest_ResizeNumBytes_P, DataStaysIntact) { - uint32_t oldNumberOfLeaves = std::max(UINT64_C(1), ceilDivision(tree->numBytes(), static_cast(nodeStore->layout().maxBytesPerLeaf()))); + const uint32_t oldNumberOfLeaves = std::max(UINT64_C(1), ceilDivision(tree->numBytes(), static_cast(nodeStore->layout().maxBytesPerLeaf()))); TwoLevelDataFixture data(nodeStore, TwoLevelDataFixture::SizePolicy::Unchanged); - BlockId blockId = tree->blockId(); + const BlockId blockId = tree->blockId(); cpputils::destruct(std::move(tree)); data.FillInto(nodeStore->load(blockId).get().get()); @@ -244,7 +244,7 @@ TEST_P(DataTreeTest_ResizeNumBytes_P, UnneededBlocksGetDeletedWhenShrinking) { TEST_F(DataTreeTest_ResizeNumBytes, ResizeToZero_NumBytesIsCorrect) { auto tree = CreateThreeLevelTreeWithThreeChildrenAndLastLeafSize(10u); tree->resizeNumBytes(0); - BlockId blockId = tree->blockId(); + const BlockId blockId = tree->blockId(); cpputils::destruct(std::move(tree)); auto leaf = LoadLeafNode(blockId); EXPECT_EQ(0u, leaf->numBytes()); @@ -252,7 +252,7 @@ TEST_F(DataTreeTest_ResizeNumBytes, ResizeToZero_NumBytesIsCorrect) { TEST_F(DataTreeTest_ResizeNumBytes, ResizeToZero_blockIdDoesntChange) { auto tree = CreateThreeLevelTreeWithThreeChildrenAndLastLeafSize(10u); - BlockId blockId = tree->blockId(); + const BlockId blockId = tree->blockId(); tree->resizeNumBytes(0); tree->flush(); EXPECT_EQ(blockId, tree->blockId()); diff --git a/test/blobstore/implementations/onblocks/datatreestore/LeafTraverserTest.cpp b/test/blobstore/implementations/onblocks/datatreestore/LeafTraverserTest.cpp index 966e3d53..a8f951c9 100644 --- a/test/blobstore/implementations/onblocks/datatreestore/LeafTraverserTest.cpp +++ b/test/blobstore/implementations/onblocks/datatreestore/LeafTraverserTest.cpp @@ -50,7 +50,7 @@ public: } void EXPECT_CREATE_LEAF(uint32_t leafIndex) { - uint64_t maxBytesPerLeaf = nodeStore->layout().maxBytesPerLeaf(); + const uint64_t maxBytesPerLeaf = nodeStore->layout().maxBytesPerLeaf(); EXPECT_CALL(traversor, calledCreateLeaf(Eq(leafIndex))).Times(1).WillOnce(Invoke([maxBytesPerLeaf] (uint32_t) { return make_shared(maxBytesPerLeaf); })); @@ -256,7 +256,7 @@ TEST_F(LeafTraverserTest, TraverseFirstLeafOfThreelevelTree) { TEST_F(LeafTraverserTest, TraverseLastLeafOfThreelevelTree) { auto root = CreateThreeLevel(); - uint32_t numLeaves = nodeStore->layout().maxChildrenPerInnerNode() * 5 + 3; + const uint32_t numLeaves = nodeStore->layout().maxChildrenPerInnerNode() * 5 + 3; EXPECT_TRAVERSE_LEAF(LoadInnerNode(root->readLastChild().blockId())->readLastChild().blockId(), true, numLeaves-1); TraverseLeaves(std::move(root), numLeaves-1, numLeaves, true); @@ -264,7 +264,7 @@ TEST_F(LeafTraverserTest, TraverseLastLeafOfThreelevelTree) { TEST_F(LeafTraverserTest, TraverseMiddleLeafOfThreelevelTree) { auto root = CreateThreeLevel(); - uint32_t wantedLeafIndex = nodeStore->layout().maxChildrenPerInnerNode() * 2 + 5; + const uint32_t wantedLeafIndex = nodeStore->layout().maxChildrenPerInnerNode() * 2 + 5; EXPECT_TRAVERSE_LEAF(LoadInnerNode(root->readChild(2).blockId())->readChild(5).blockId(), false, wantedLeafIndex); TraverseLeaves(std::move(root), wantedLeafIndex, wantedLeafIndex+1, true); diff --git a/test/blobstore/implementations/onblocks/utils/CeilDivisionTest.cpp b/test/blobstore/implementations/onblocks/utils/CeilDivisionTest.cpp index 959c3b8e..bf75358e 100644 --- a/test/blobstore/implementations/onblocks/utils/CeilDivisionTest.cpp +++ b/test/blobstore/implementations/onblocks/utils/CeilDivisionTest.cpp @@ -82,7 +82,7 @@ TEST_F(CeilDivisionTest, DivideLargeByItself) { } TEST_F(CeilDivisionTest, 64bit) { - uint64_t base = UINT64_C(1024)*1024*1024*1024; + const uint64_t base = UINT64_C(1024)*1024*1024*1024; EXPECT_GT(base, std::numeric_limits::max()); EXPECT_EQ(base/1024, ceilDivision(base, UINT64_C(1024))); } diff --git a/test/blobstore/implementations/onblocks/utils/CeilLogTest.cpp b/test/blobstore/implementations/onblocks/utils/CeilLogTest.cpp index c5bb67d4..bb48a7fb 100644 --- a/test/blobstore/implementations/onblocks/utils/CeilLogTest.cpp +++ b/test/blobstore/implementations/onblocks/utils/CeilLogTest.cpp @@ -26,7 +26,7 @@ TEST_F(CeilLogTest, Log3_4) { } TEST_F(CeilLogTest, 64bit) { - uint64_t value = UINT64_C(1024)*1024*1024*1024; + const uint64_t value = UINT64_C(1024)*1024*1024*1024; EXPECT_GT(value, std::numeric_limits::max()); EXPECT_EQ(4u, ceilLog(UINT64_C(1024), value)); } diff --git a/test/blobstore/implementations/onblocks/utils/IntPowTest.cpp b/test/blobstore/implementations/onblocks/utils/IntPowTest.cpp index c6118209..d0ce9526 100644 --- a/test/blobstore/implementations/onblocks/utils/IntPowTest.cpp +++ b/test/blobstore/implementations/onblocks/utils/IntPowTest.cpp @@ -71,7 +71,7 @@ TEST_F(IntPowTest, ArbitraryNumbers3) { } TEST_F(IntPowTest, 64bit) { - uint64_t value = UINT64_C(1024)*1024*1024*1024; + const uint64_t value = UINT64_C(1024)*1024*1024*1024; EXPECT_GT(value, std::numeric_limits::max()); EXPECT_EQ(value*value*value, intPow(value, UINT64_C(3))); } diff --git a/test/blobstore/implementations/onblocks/utils/MaxZeroSubtractionTest.cpp b/test/blobstore/implementations/onblocks/utils/MaxZeroSubtractionTest.cpp index 6a3b6fbd..33fc420e 100644 --- a/test/blobstore/implementations/onblocks/utils/MaxZeroSubtractionTest.cpp +++ b/test/blobstore/implementations/onblocks/utils/MaxZeroSubtractionTest.cpp @@ -78,13 +78,13 @@ TEST_F(MaxZeroSubtractionTest, SubtractFromZero3) { } TEST_F(MaxZeroSubtractionTest, 64bit_valid) { - uint64_t value = UINT64_C(1024)*1024*1024*1024; + const uint64_t value = UINT64_C(1024)*1024*1024*1024; EXPECT_GT(value, std::numeric_limits::max()); EXPECT_EQ(value*1024-value, maxZeroSubtraction(value*1024, value)); } TEST_F(MaxZeroSubtractionTest, 64bit_zero) { - uint64_t value = UINT64_C(1024)*1024*1024*1024; + const uint64_t value = UINT64_C(1024)*1024*1024*1024; EXPECT_GT(value, std::numeric_limits::max()); EXPECT_EQ(0u, maxZeroSubtraction(value, value*1024)); } diff --git a/test/blockstore/implementations/caching/CachingBlockStore2Test_Specific.cpp b/test/blockstore/implementations/caching/CachingBlockStore2Test_Specific.cpp index 17de609f..90da503e 100644 --- a/test/blockstore/implementations/caching/CachingBlockStore2Test_Specific.cpp +++ b/test/blockstore/implementations/caching/CachingBlockStore2Test_Specific.cpp @@ -1,6 +1,8 @@ #include + #include "blockstore/implementations/caching/CachingBlockStore2.h" #include "blockstore/implementations/inmemory/InMemoryBlockStore2.h" +#include using ::testing::Test; diff --git a/test/blockstore/implementations/caching/cache/CacheTest_MoveConstructor.cpp b/test/blockstore/implementations/caching/cache/CacheTest_MoveConstructor.cpp index c4377ab0..3cb78a54 100644 --- a/test/blockstore/implementations/caching/cache/CacheTest_MoveConstructor.cpp +++ b/test/blockstore/implementations/caching/cache/CacheTest_MoveConstructor.cpp @@ -21,15 +21,15 @@ public: TEST_F(CacheTest_MoveConstructor, MoveIntoCache) { cache->push(MinimalKeyType::create(0), CopyableMovableValueType(2)); - CopyableMovableValueType val = cache->pop(MinimalKeyType::create(0)).value(); + const CopyableMovableValueType val = cache->pop(MinimalKeyType::create(0)).value(); val.value(); //Access it to avoid the compiler optimizing the assignment away EXPECT_EQ(0, CopyableMovableValueType::numCopyConstructorCalled); } TEST_F(CacheTest_MoveConstructor, CopyIntoCache) { - CopyableMovableValueType value(2); + const CopyableMovableValueType value(2); cache->push(MinimalKeyType::create(0), value); - CopyableMovableValueType val = cache->pop(MinimalKeyType::create(0)).value(); + const CopyableMovableValueType val = cache->pop(MinimalKeyType::create(0)).value(); val.value(); //Access it to avoid the compiler optimizing the assignment away EXPECT_EQ(1, CopyableMovableValueType::numCopyConstructorCalled); } diff --git a/test/blockstore/implementations/caching/cache/PeriodicTaskTest.cpp b/test/blockstore/implementations/caching/cache/PeriodicTaskTest.cpp index 5dc7c739..099984d1 100644 --- a/test/blockstore/implementations/caching/cache/PeriodicTaskTest.cpp +++ b/test/blockstore/implementations/caching/cache/PeriodicTaskTest.cpp @@ -18,7 +18,7 @@ public: AtomicCounter(int count): _mutex(), _cv(), _counter(count) {} void decrease() { - unique_lock lock(_mutex); + const unique_lock lock(_mutex); --_counter; _cv.notify_all(); } @@ -37,13 +37,13 @@ class PeriodicTaskTest: public Test { }; TEST_F(PeriodicTaskTest, DoesntDeadlockInDestructorWhenDestructedImmediately) { - PeriodicTask task([](){}, 1, "test"); + const PeriodicTask task([](){}, 1, "test"); } TEST_F(PeriodicTaskTest, CallsCallbackAtLeast10Times) { AtomicCounter counter(10); - PeriodicTask task([&counter](){ + const PeriodicTask task([&counter](){ counter.decrease(); }, 0.001, "test"); @@ -53,11 +53,11 @@ TEST_F(PeriodicTaskTest, CallsCallbackAtLeast10Times) { TEST_F(PeriodicTaskTest, DoesntCallCallbackAfterDestruction) { std::atomic callCount(0); { - PeriodicTask task([&callCount](){ + const PeriodicTask task([&callCount](){ callCount += 1; }, 0.001, "test"); } - int callCountDirectlyAfterDestruction = callCount; + const int callCountDirectlyAfterDestruction = callCount; boost::this_thread::sleep_for(boost::chrono::seconds(1)); EXPECT_EQ(callCountDirectlyAfterDestruction, callCount); } diff --git a/test/blockstore/implementations/caching/cache/QueueMapTest_MoveConstructor.cpp b/test/blockstore/implementations/caching/cache/QueueMapTest_MoveConstructor.cpp index 2a0126ec..cf893210 100644 --- a/test/blockstore/implementations/caching/cache/QueueMapTest_MoveConstructor.cpp +++ b/test/blockstore/implementations/caching/cache/QueueMapTest_MoveConstructor.cpp @@ -21,30 +21,30 @@ public: TEST_F(QueueMapTest_MoveConstructor, PushingAndPopping_MoveIntoMap) { map->push(MinimalKeyType::create(0), CopyableMovableValueType(2)); - CopyableMovableValueType val = map->pop().value(); + const CopyableMovableValueType val = map->pop().value(); val.value(); //Access it to avoid the compiler optimizing the assignment away EXPECT_EQ(0, CopyableMovableValueType::numCopyConstructorCalled); } TEST_F(QueueMapTest_MoveConstructor, PushingAndPoppingPerKey_MoveIntoMap) { map->push(MinimalKeyType::create(0), CopyableMovableValueType(2)); - CopyableMovableValueType val = map->pop(MinimalKeyType::create(0)).value(); + const CopyableMovableValueType val = map->pop(MinimalKeyType::create(0)).value(); val.value(); //Access it to avoid the compiler optimizing the assignment away EXPECT_EQ(0, CopyableMovableValueType::numCopyConstructorCalled); } TEST_F(QueueMapTest_MoveConstructor, PushingAndPopping_CopyIntoMap) { - CopyableMovableValueType value(2); + const CopyableMovableValueType value(2); map->push(MinimalKeyType::create(0), value); - CopyableMovableValueType val = map->pop().value(); + const CopyableMovableValueType val = map->pop().value(); val.value(); //Access it to avoid the compiler optimizing the assignment away EXPECT_EQ(1, CopyableMovableValueType::numCopyConstructorCalled); } TEST_F(QueueMapTest_MoveConstructor, PushingAndPoppingPerKey_CopyIntoMap) { - CopyableMovableValueType value(2); + const CopyableMovableValueType value(2); map->push(MinimalKeyType::create(0), value); - CopyableMovableValueType val = map->pop(MinimalKeyType::create(0)).value(); + const CopyableMovableValueType val = map->pop(MinimalKeyType::create(0)).value(); val.value(); //Access it to avoid the compiler optimizing the assignment away EXPECT_EQ(1, CopyableMovableValueType::numCopyConstructorCalled); } diff --git a/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.cpp b/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.cpp index 76fae6fe..f175dc30 100644 --- a/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.cpp +++ b/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.cpp @@ -39,6 +39,6 @@ boost::optional QueueMapTest::peek() { return elem.value().value(); } -int QueueMapTest::size() { +uint32_t QueueMapTest::size() { return _map->size(); } diff --git a/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.h b/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.h index c4d4cf00..c8eaf7a5 100644 --- a/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.h +++ b/test/blockstore/implementations/caching/cache/testutils/QueueMapTest.h @@ -15,13 +15,13 @@ class QueueMapTest: public ::testing::Test { public: QueueMapTest(); - ~QueueMapTest(); + ~QueueMapTest() override; void push(int key, int value); boost::optional pop(); boost::optional pop(int key); boost::optional peek(); - int size(); + uint32_t size(); private: cpputils::unique_ref> _map; diff --git a/test/blockstore/implementations/compressing/compressors/testutils/CompressorTest.cpp b/test/blockstore/implementations/compressing/compressors/testutils/CompressorTest.cpp index 254795e1..2bf760bc 100644 --- a/test/blockstore/implementations/compressing/compressors/testutils/CompressorTest.cpp +++ b/test/blockstore/implementations/compressing/compressors/testutils/CompressorTest.cpp @@ -12,7 +12,7 @@ class CompressorTest: public ::testing::Test { public: void EXPECT_COMPRESS_AND_DECOMPRESS_IS_IDENTITY(const Data &data) { Data compressed = Compressor::Compress(data); - Data decompressed = Compressor::Decompress(compressed.data(), compressed.size()); + const Data decompressed = Compressor::Decompress(compressed.data(), compressed.size()); EXPECT_EQ(data, decompressed); } }; @@ -20,12 +20,12 @@ public: TYPED_TEST_SUITE_P(CompressorTest); TYPED_TEST_P(CompressorTest, Empty) { - Data empty(0); + const Data empty(0); this->EXPECT_COMPRESS_AND_DECOMPRESS_IS_IDENTITY(empty); } TYPED_TEST_P(CompressorTest, ArbitraryData) { - Data fixture = DataFixture::generate(10240); + const Data fixture = DataFixture::generate(10240); this->EXPECT_COMPRESS_AND_DECOMPRESS_IS_IDENTITY(fixture); } @@ -53,7 +53,7 @@ TYPED_TEST_P(CompressorTest, RunsAndArbitrary) { TYPED_TEST_P(CompressorTest, LargeData) { // this is larger than what fits into 16bit (16bit are for example used as run length indicator in RunLengthEncoding) - Data fixture = DataFixture::generate(200000); + const Data fixture = DataFixture::generate(200000); this->EXPECT_COMPRESS_AND_DECOMPRESS_IS_IDENTITY(fixture); } diff --git a/test/blockstore/implementations/encrypted/EncryptedBlockStoreTest_Specific.cpp b/test/blockstore/implementations/encrypted/EncryptedBlockStoreTest_Specific.cpp index 28101a56..c0b2b5ca 100644 --- a/test/blockstore/implementations/encrypted/EncryptedBlockStoreTest_Specific.cpp +++ b/test/blockstore/implementations/encrypted/EncryptedBlockStoreTest_Specific.cpp @@ -6,6 +6,8 @@ #include "../../testutils/gtest_printers.h" #include +#include + using ::testing::Test; using cpputils::DataFixture; diff --git a/test/blockstore/implementations/integrity/IntegrityBlockStoreTest_Specific.cpp b/test/blockstore/implementations/integrity/IntegrityBlockStoreTest_Specific.cpp index 12aa5cf6..18440331 100644 --- a/test/blockstore/implementations/integrity/IntegrityBlockStoreTest_Specific.cpp +++ b/test/blockstore/implementations/integrity/IntegrityBlockStoreTest_Specific.cpp @@ -4,7 +4,9 @@ #include "blockstore/utils/BlockStoreUtils.h" #include #include + #include "../../testutils/gtest_printers.h" +#include using ::testing::Test; @@ -15,7 +17,6 @@ using cpputils::make_unique_ref; using cpputils::TempFile; using cpputils::serialize; using cpputils::deserialize; -using boost::none; using std::unique_ptr; using blockstore::inmemory::InMemoryBlockStore2; @@ -90,7 +91,7 @@ public: void decreaseVersionNumber(const blockstore::BlockId &blockId) { auto baseBlock = baseBlockStore->load(blockId).value(); void* versionPtr = static_cast(baseBlock.data()) + IntegrityBlockStore2::VERSION_HEADER_OFFSET; - uint64_t version = deserialize(versionPtr); + const uint64_t version = deserialize(versionPtr); ASSERT(version > 1, "Can't decrease the lowest allowed version number"); serialize(versionPtr, version-1); baseBlockStore->store(blockId, baseBlock); @@ -99,7 +100,7 @@ public: void increaseVersionNumber(const blockstore::BlockId &blockId) { auto baseBlock = baseBlockStore->load(blockId).value(); void* versionPtr = static_cast(baseBlock.data()) + IntegrityBlockStore2::VERSION_HEADER_OFFSET; - uint64_t version = deserialize(versionPtr); + const uint64_t version = deserialize(versionPtr); serialize(versionPtr, version+1); baseBlockStore->store(blockId, baseBlock); } @@ -107,7 +108,7 @@ public: void changeClientId(const blockstore::BlockId &blockId) { auto baseBlock = baseBlockStore->load(blockId).value(); void* clientIdPtr = static_cast(baseBlock.data()) + IntegrityBlockStore2::CLIENTID_HEADER_OFFSET; - uint64_t clientId = deserialize(clientIdPtr); + const uint64_t clientId = deserialize(clientIdPtr); serialize(clientIdPtr, clientId+1); baseBlockStore->store(blockId, baseBlock); } @@ -135,7 +136,7 @@ constexpr uint32_t IntegrityBlockStoreTestload(blockId)); @@ -145,7 +146,7 @@ TEST_F(IntegrityBlockStoreTest_Default, RollbackPrevention_DoesntAllowDecreasing // Test that a decreasing version number is allowed if allowIntegrityViolations is set. TEST_F(IntegrityBlockStoreTest_AllowIntegrityViolations, RollbackPrevention_AllowsDecreasingVersionNumberForSameClient_1) { auto blockId = CreateBlockReturnKey(); - Data oldBaseBlock = loadBaseBlock(blockId); + const Data oldBaseBlock = loadBaseBlock(blockId); modifyBlock(blockId); rollbackBaseBlock(blockId, oldBaseBlock); EXPECT_NE(boost::none, blockStore->load(blockId)); @@ -202,7 +203,7 @@ TEST_F(IntegrityBlockStoreTest_Default, RollbackPrevention_DoesntAllowSameVersio auto blockId = CreateBlockReturnKey(); // Increase the version number modifyBlock(blockId); - Data oldBaseBlock = loadBaseBlock(blockId); + const Data oldBaseBlock = loadBaseBlock(blockId); // Fake a modification by a different client with lower version numbers changeClientId(blockId); loadBlock(blockId); // make the block store know about this other client's modification @@ -217,7 +218,7 @@ TEST_F(IntegrityBlockStoreTest_AllowIntegrityViolations, RollbackPrevention_Allo auto blockId = CreateBlockReturnKey(); // Increase the version number modifyBlock(blockId); - Data oldBaseBlock = loadBaseBlock(blockId); + const Data oldBaseBlock = loadBaseBlock(blockId); // Fake a modification by a different client with lower version numbers changeClientId(blockId); loadBlock(blockId); // make the block store know about this other client's modification @@ -340,7 +341,7 @@ TEST_F(IntegrityBlockStoreTest_AllowIntegrityViolations_MissingBlockIsIntegrityV TEST_F(IntegrityBlockStoreTest_Default, LoadingWithDifferentBlockIdFails) { auto blockId = CreateBlockReturnKey(); - blockstore::BlockId key2 = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); + const blockstore::BlockId key2 = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); baseBlockStore->store(key2, baseBlockStore->load(blockId).value()); EXPECT_EQ(boost::none, blockStore->load(key2)); EXPECT_TRUE(onIntegrityViolation.wasCalled()); @@ -348,7 +349,7 @@ TEST_F(IntegrityBlockStoreTest_Default, LoadingWithDifferentBlockIdFails) { TEST_F(IntegrityBlockStoreTest_AllowIntegrityViolations, LoadingWithDifferentBlockIdDoesntFail) { auto blockId = CreateBlockReturnKey(); - blockstore::BlockId key2 = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); + const blockstore::BlockId key2 = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); baseBlockStore->store(key2, baseBlockStore->load(blockId).value()); EXPECT_NE(boost::none, blockStore->load(key2)); EXPECT_FALSE(onIntegrityViolation.wasCalled()); diff --git a/test/blockstore/implementations/integrity/KnownBlockVersionsTest.cpp b/test/blockstore/implementations/integrity/KnownBlockVersionsTest.cpp index 772fb65d..ac2752a3 100644 --- a/test/blockstore/implementations/integrity/KnownBlockVersionsTest.cpp +++ b/test/blockstore/implementations/integrity/KnownBlockVersionsTest.cpp @@ -230,24 +230,24 @@ TEST_F(KnownBlockVersionsTest, checkAndUpdate_doesntAllowRollbackToOldClientWith } TEST_F(KnownBlockVersionsTest, saveAndLoad_empty) { - TempFile stateFile(false); + const TempFile stateFile(false); { - KnownBlockVersions _1(stateFile.path(), myClientId); + const KnownBlockVersions _1(stateFile.path(), myClientId); } EXPECT_TRUE(KnownBlockVersions(stateFile.path(), myClientId).checkAndUpdateVersion(clientId, blockId, 1)); } TEST_F(KnownBlockVersionsTest, saveAndLoad_oneentry) { - TempFile stateFile(false); + const TempFile stateFile(false); EXPECT_TRUE(KnownBlockVersions(stateFile.path(), myClientId).checkAndUpdateVersion(clientId, blockId, 100)); - KnownBlockVersions obj(stateFile.path(), myClientId); + const KnownBlockVersions obj(stateFile.path(), myClientId); EXPECT_EQ(100u, obj.getBlockVersion(clientId, blockId)); } TEST_F(KnownBlockVersionsTest, saveAndLoad_threeentries) { - TempFile stateFile(false); + const TempFile stateFile(false); { KnownBlockVersions obj(stateFile.path(), myClientId); EXPECT_TRUE(obj.checkAndUpdateVersion(obj.myClientId(), blockId, 100)); @@ -255,7 +255,7 @@ TEST_F(KnownBlockVersionsTest, saveAndLoad_threeentries) { EXPECT_TRUE(obj.checkAndUpdateVersion(clientId, blockId, 150)); } - KnownBlockVersions obj(stateFile.path(), myClientId); + const KnownBlockVersions obj(stateFile.path(), myClientId); EXPECT_EQ(100u, obj.getBlockVersion(obj.myClientId(), blockId)); EXPECT_EQ(50u, obj.getBlockVersion(obj.myClientId(), blockId2)); EXPECT_EQ(150u, obj.getBlockVersion(clientId, blockId)); @@ -313,7 +313,7 @@ TEST_F(KnownBlockVersionsTest, blockShouldExist_deletedBlock) { } TEST_F(KnownBlockVersionsTest, path) { - KnownBlockVersions obj(stateFile.path(), myClientId); + const KnownBlockVersions obj(stateFile.path(), myClientId); EXPECT_EQ(stateFile.path(), obj.path()); } diff --git a/test/blockstore/implementations/ondisk/OnDiskBlockStoreTest_Specific.cpp b/test/blockstore/implementations/ondisk/OnDiskBlockStoreTest_Specific.cpp index eac53467..61b38f1d 100644 --- a/test/blockstore/implementations/ondisk/OnDiskBlockStoreTest_Specific.cpp +++ b/test/blockstore/implementations/ondisk/OnDiskBlockStoreTest_Specific.cpp @@ -2,6 +2,8 @@ #include "blockstore/implementations/ondisk/OnDiskBlockStore2.h" #include +#include + using ::testing::Test; using cpputils::TempDir; diff --git a/test/blockstore/implementations/parallelaccess/ParallelAccessBlockStoreTest_Specific.cpp b/test/blockstore/implementations/parallelaccess/ParallelAccessBlockStoreTest_Specific.cpp index b59f7370..5da23f83 100644 --- a/test/blockstore/implementations/parallelaccess/ParallelAccessBlockStoreTest_Specific.cpp +++ b/test/blockstore/implementations/parallelaccess/ParallelAccessBlockStoreTest_Specific.cpp @@ -1,6 +1,8 @@ #include + #include "blockstore/implementations/parallelaccess/ParallelAccessBlockStore.h" #include "blockstore/implementations/testfake/FakeBlockStore.h" +#include using ::testing::Test; diff --git a/test/blockstore/interface/BlockStore2Test.cpp b/test/blockstore/interface/BlockStore2Test.cpp index d11230a3..57cd384b 100644 --- a/test/blockstore/interface/BlockStore2Test.cpp +++ b/test/blockstore/interface/BlockStore2Test.cpp @@ -78,7 +78,7 @@ TEST_F(BlockStore2Test, DataIsPassedThrough1024) { } TEST_F(BlockStore2Test, BlockIdIsCorrect) { - Data data = createDataWithSize(1024); + const Data data = createDataWithSize(1024); EXPECT_CALL(blockStoreMock, createBlockId()).WillOnce(Return(blockId1)); EXPECT_CALL(blockStoreMock, tryCreate(blockId1, testing::_)).WillOnce(Return(true)); EXPECT_EQ(blockId1, blockStore.create(data)); @@ -98,7 +98,7 @@ TEST_F(BlockStore2Test, TwoBlocksGetDifferentIds) { return true; })); - Data data = createDataWithSize(1024); + const Data data = createDataWithSize(1024); EXPECT_EQ(blockId1, blockStore.create(data)); EXPECT_EQ(blockId2, blockStore.create(data)); } diff --git a/test/blockstore/interface/BlockStoreTest.cpp b/test/blockstore/interface/BlockStoreTest.cpp index 65f375d8..a9d8b1d0 100644 --- a/test/blockstore/interface/BlockStoreTest.cpp +++ b/test/blockstore/interface/BlockStoreTest.cpp @@ -92,7 +92,7 @@ TEST_F(BlockStoreTest, DataIsPassedThrough1024) { } TEST_F(BlockStoreTest, BlockIdIsCorrect) { - Data data = createDataWithSize(1024); + const Data data = createDataWithSize(1024); EXPECT_CALL(blockStoreMock, createBlockId()).WillOnce(Return(blockId1)); EXPECT_CALL(blockStoreMock, tryCreate(blockId1, testing::_)).WillOnce(ReturnNewBlockMock); blockStore.create(data); @@ -112,7 +112,7 @@ TEST_F(BlockStoreTest, TwoBlocksGetDifferentIds) { return optional>(unique_ref(make_unique_ref())); })); - Data data = createDataWithSize(1024); + const Data data = createDataWithSize(1024); blockStore.create(data); blockStore.create(data); } diff --git a/test/blockstore/testutils/BlockStore2Test.h b/test/blockstore/testutils/BlockStore2Test.h index d6de1b7d..29fe311d 100644 --- a/test/blockstore/testutils/BlockStore2Test.h +++ b/test/blockstore/testutils/BlockStore2Test.h @@ -56,23 +56,23 @@ public: TYPED_TEST_SUITE_P(BlockStore2Test); TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenCallingTryCreateOnExistingBlock_thenFails) { - blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); EXPECT_FALSE(this->blockStore->tryCreate(blockId, cpputils::Data(1024))); } TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenCallingTryCreateOnNonExistingBlock_thenSucceeds) { - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); EXPECT_TRUE(this->blockStore->tryCreate(blockId, cpputils::Data(1024))); } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenCallingTryCreateOnNonExistingBlock_thenSucceeds) { this->blockStore->create(cpputils::Data(512)); - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); EXPECT_TRUE(this->blockStore->tryCreate(blockId, cpputils::Data(1024))); } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenLoadExistingBlock_thenSucceeds) { - blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); EXPECT_NE(boost::none, this->blockStore->load(blockId)); } @@ -88,7 +88,7 @@ TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenLoadNonexistingBlock_t } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenStoringExistingBlock_thenSucceeds) { - blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); this->blockStore->store(blockId, cpputils::Data(1024)); } @@ -104,20 +104,20 @@ TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenStoringNonexistingBloc } TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenCreatingTwoBlocks_thenTheyGetDifferentKeys) { - blockstore::BlockId blockId1 = this->blockStore->create(cpputils::Data(1024)); - blockstore::BlockId blockId2 = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId1 = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId2 = this->blockStore->create(cpputils::Data(1024)); EXPECT_NE(blockId1, blockId2); } TYPED_TEST_P(BlockStore2Test, givenOtherwiseEmptyBlockStore_whenRemovingBlock_thenBlockIsNotLoadableAnymore) { - blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); EXPECT_NE(boost::none, this->blockStore->load(blockId)); EXPECT_TRUE(this->blockStore->remove(blockId)); EXPECT_EQ(boost::none, this->blockStore->load(blockId)); } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenRemovingBlock_thenBlockIsNotLoadableAnymore) { - blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); this->blockStore->create(cpputils::Data(512)); EXPECT_NE(boost::none, this->blockStore->load(blockId)); EXPECT_TRUE(this->blockStore->remove(blockId)); @@ -125,12 +125,12 @@ TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenRemovingBlock_thenBloc } TYPED_TEST_P(BlockStore2Test, givenOtherwiseEmptyBlockStore_whenRemovingExistingBlock_thenSucceeds) { - blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); EXPECT_TRUE(this->blockStore->remove(blockId)); } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenRemovingExistingBlock_thenSucceeds) { - blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); + const blockstore::BlockId blockId = this->blockStore->create(cpputils::Data(1024)); this->blockStore->create(cpputils::Data(512)); EXPECT_EQ(true, this->blockStore->remove(blockId)); } @@ -142,8 +142,8 @@ TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenRemovingNonexistingBlock_ } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenRemovingNonexistingBlock_thenFails) { - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); - blockstore::BlockId differentKey = blockstore::BlockId::FromString("290AC2C7097274A389EE14B91B72B493"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); + const blockstore::BlockId differentKey = blockstore::BlockId::FromString("290AC2C7097274A389EE14B91B72B493"); ASSERT_TRUE(this->blockStore->tryCreate(blockId, cpputils::Data(1024))); EXPECT_EQ(false, this->blockStore->remove(differentKey)); } @@ -162,7 +162,7 @@ TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenCreatingAndLoadingEmpt } TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenCreatingAndLoadingNonEmptyBlock_thenCorrectBlockLoads) { - cpputils::Data data = cpputils::DataFixture::generate(1024); + const cpputils::Data data = cpputils::DataFixture::generate(1024); auto blockId = this->blockStore->create(data.copy()); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(loaded, data); @@ -170,21 +170,21 @@ TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenCreatingAndLoadingNonEmpt TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenCreatingAndLoadingNonEmptyBlock_thenCorrectBlockLoads) { this->blockStore->create(cpputils::Data(512)); - cpputils::Data data = cpputils::DataFixture::generate(1024); + const cpputils::Data data = cpputils::DataFixture::generate(1024); auto blockId = this->blockStore->create(data.copy()); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(loaded, data); } TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenTryCreatingAndLoadingEmptyBlock_thenCorrectBlockLoads) { - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); ASSERT_TRUE(this->blockStore->tryCreate(blockId, cpputils::Data(0))); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(0u, loaded.size()); } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenTryCreatingAndLoadingEmptyBlock_thenCorrectBlockLoads) { - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); this->blockStore->create(cpputils::Data(512)); ASSERT_TRUE(this->blockStore->tryCreate(blockId, cpputils::Data(0))); auto loaded = this->blockStore->load(blockId).value(); @@ -192,17 +192,17 @@ TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenTryCreatingAndLoadingE } TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenTryCreatingAndLoadingNonEmptyBlock_thenCorrectBlockLoads) { - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); - cpputils::Data data = cpputils::DataFixture::generate(1024); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); + const cpputils::Data data = cpputils::DataFixture::generate(1024); ASSERT_TRUE(this->blockStore->tryCreate(blockId, data.copy())); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(loaded, data); } TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenTryCreatingAndLoadingNonEmptyBlock_thenCorrectBlockLoads) { - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772973"); this->blockStore->create(cpputils::Data(512)); - cpputils::Data data = cpputils::DataFixture::generate(1024); + const cpputils::Data data = cpputils::DataFixture::generate(1024); ASSERT_TRUE(this->blockStore->tryCreate(blockId, data.copy())); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(loaded, data); @@ -225,7 +225,7 @@ TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenStoringAndLoadingNonEx TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenStoringAndLoadingNonExistingNonEmptyBlock_thenCorrectBlockLoads) { const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); - cpputils::Data data = cpputils::DataFixture::generate(1024); + const cpputils::Data data = cpputils::DataFixture::generate(1024); this->blockStore->store(blockId, data.copy()); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(data, loaded); @@ -234,7 +234,7 @@ TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenStoringAndLoadingNonExist TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenStoringAndLoadingNonExistingNonEmptyBlock_thenCorrectBlockLoads) { this->blockStore->create(cpputils::Data(512)); const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); - cpputils::Data data = cpputils::DataFixture::generate(1024); + const cpputils::Data data = cpputils::DataFixture::generate(1024); this->blockStore->store(blockId, data.copy()); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(data, loaded); @@ -257,7 +257,7 @@ TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenStoringAndLoadingExist TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenStoringAndLoadingExistingNonEmptyBlock_thenCorrectBlockLoads) { auto blockId = this->blockStore->create(cpputils::Data(512)); - cpputils::Data data = cpputils::DataFixture::generate(1024); + const cpputils::Data data = cpputils::DataFixture::generate(1024); this->blockStore->store(blockId, data.copy()); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(data, loaded); @@ -266,7 +266,7 @@ TYPED_TEST_P(BlockStore2Test, givenEmptyBlockStore_whenStoringAndLoadingExisting TYPED_TEST_P(BlockStore2Test, givenNonEmptyBlockStore_whenStoringAndLoadingExistingNonEmptyBlock_thenCorrectBlockLoads) { this->blockStore->create(cpputils::Data(512)); auto blockId = this->blockStore->create(cpputils::Data(512)); - cpputils::Data data = cpputils::DataFixture::generate(1024); + const cpputils::Data data = cpputils::DataFixture::generate(1024); this->blockStore->store(blockId, data.copy()); auto loaded = this->blockStore->load(blockId).value(); EXPECT_EQ(data, loaded); @@ -296,7 +296,7 @@ TYPED_TEST_P(BlockStore2Test, NumBlocksIsCorrectAfterCreatingOneBlock) { TYPED_TEST_P(BlockStore2Test, NumBlocksIsCorrectAfterRemovingTheLastBlock) { auto blockStore = this->fixture.createBlockStore(); - blockstore::BlockId blockId = blockStore->create(cpputils::Data(1)); + const blockstore::BlockId blockId = blockStore->create(cpputils::Data(1)); EXPECT_TRUE(blockStore->remove(blockId)); EXPECT_EQ(0u, blockStore->numBlocks()); } @@ -310,7 +310,7 @@ TYPED_TEST_P(BlockStore2Test, NumBlocksIsCorrectAfterCreatingTwoBlocks) { TYPED_TEST_P(BlockStore2Test, NumBlocksIsCorrectAfterRemovingABlock) { auto blockStore = this->fixture.createBlockStore(); - blockstore::BlockId blockId = blockStore->create(cpputils::Data(1)); + const blockstore::BlockId blockId = blockStore->create(cpputils::Data(1)); blockStore->create(cpputils::Data(1)); EXPECT_TRUE(blockStore->remove(blockId)); EXPECT_EQ(1u, blockStore->numBlocks()); @@ -325,7 +325,7 @@ TYPED_TEST_P(BlockStore2Test, NumBlocksIsCorrectAfterStoringANewBlock) { TYPED_TEST_P(BlockStore2Test, NumBlocksIsCorrectAfterStoringAnExistingBlock) { auto blockStore = this->fixture.createBlockStore(); - blockstore::BlockId blockId = blockStore->create(cpputils::Data(1)); + const blockstore::BlockId blockId = blockStore->create(cpputils::Data(1)); blockStore->store(blockId, cpputils::Data(1)); EXPECT_EQ(1u, blockStore->numBlocks()); } @@ -385,21 +385,21 @@ TYPED_TEST_P(BlockStore2Test, ForEachBlock_doesntListRemovedBlocks_twoblocks) { TYPED_TEST_P(BlockStore2Test, TryCreateTwoBlocksWithSameBlockIdAndSameSize) { auto blockStore = this->fixture.createBlockStore(); - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); EXPECT_TRUE(blockStore->tryCreate(blockId, cpputils::Data(1024))); EXPECT_FALSE(blockStore->tryCreate(blockId, cpputils::Data(1024))); } TYPED_TEST_P(BlockStore2Test, TryCreateTwoBlocksWithSameBlockIdAndDifferentSize) { auto blockStore = this->fixture.createBlockStore(); - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); EXPECT_TRUE(blockStore->tryCreate(blockId, cpputils::Data(1024))); EXPECT_FALSE(blockStore->tryCreate(blockId, cpputils::Data(4096))); } TYPED_TEST_P(BlockStore2Test, TryCreateTwoBlocksWithSameBlockIdAndFirstNullSize) { auto blockStore = this->fixture.createBlockStore(); - blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); + const blockstore::BlockId blockId = blockstore::BlockId::FromString("1491BB4932A389EE14BC7090AC772972"); EXPECT_TRUE(blockStore->tryCreate(blockId, cpputils::Data(0))); EXPECT_FALSE(blockStore->tryCreate(blockId, cpputils::Data(1024))); } diff --git a/test/blockstore/testutils/BlockStoreTest_Data.h b/test/blockstore/testutils/BlockStoreTest_Data.h index 60b78c85..bc81f67e 100644 --- a/test/blockstore/testutils/BlockStoreTest_Data.h +++ b/test/blockstore/testutils/BlockStoreTest_Data.h @@ -28,7 +28,7 @@ public: } void TestWriteAndReadAfterLoading() { - blockstore::BlockId blockId = CreateBlockWriteToItAndReturnKey(foregroundData); + const blockstore::BlockId blockId = CreateBlockWriteToItAndReturnKey(foregroundData); auto loaded_block = blockStore->load(blockId).value(); EXPECT_DATA_READS_AS(foregroundData, *loaded_block, testData.offset, testData.count); diff --git a/test/blockstore/testutils/BlockStoreTest_Size.h b/test/blockstore/testutils/BlockStoreTest_Size.h index ea000091..90926563 100644 --- a/test/blockstore/testutils/BlockStoreTest_Size.h +++ b/test/blockstore/testutils/BlockStoreTest_Size.h @@ -7,6 +7,8 @@ #include #include +#include + class BlockStoreSizeParameterizedTest { public: BlockStoreSizeParameterizedTest(cpputils::unique_ref blockStore_, size_t size_): blockStore(std::move(blockStore_)), size(size_) {} @@ -17,7 +19,7 @@ public: } void TestLoadingUnchangedBlockHasCorrectSize() { - blockstore::BlockId blockId = CreateBlock()->blockId(); + const blockstore::BlockId blockId = CreateBlock()->blockId(); auto loaded_block = blockStore->load(blockId).value(); EXPECT_EQ(size, loaded_block->size()); } @@ -30,7 +32,7 @@ public: void TestLoadingUnchangedBlockData() { cpputils::Data data = cpputils::DataFixture::generate(size); - blockstore::BlockId blockId = blockStore->create(data)->blockId(); + const blockstore::BlockId blockId = blockStore->create(data)->blockId(); auto loaded_block = blockStore->load(blockId).value(); EXPECT_EQ(0, std::memcmp(data.data(), loaded_block->data(), size)); } @@ -50,7 +52,7 @@ public: } void TestAfterCreate_FlushingDoesntChangeBlock() { - cpputils::Data randomData = cpputils::DataFixture::generate(size); + const cpputils::Data randomData = cpputils::DataFixture::generate(size); auto block = CreateBlock(); WriteDataToBlock(block.get(), randomData); block->flush(); @@ -59,7 +61,7 @@ public: } void TestAfterLoad_FlushingDoesntChangeBlock() { - cpputils::Data randomData = cpputils::DataFixture::generate(size); + const cpputils::Data randomData = cpputils::DataFixture::generate(size); auto block = CreateBlockAndLoadIt(); WriteDataToBlock(block.get(), randomData); block->flush(); @@ -68,7 +70,7 @@ public: } void TestAfterCreate_FlushesWhenDestructed() { - cpputils::Data randomData = cpputils::DataFixture::generate(size); + const cpputils::Data randomData = cpputils::DataFixture::generate(size); blockstore::BlockId blockId = blockstore::BlockId::Null(); { auto block = blockStore->create(cpputils::Data(size)); @@ -80,7 +82,7 @@ public: } void TestAfterLoad_FlushesWhenDestructed() { - cpputils::Data randomData = cpputils::DataFixture::generate(size); + const cpputils::Data randomData = cpputils::DataFixture::generate(size); blockstore::BlockId blockId = blockstore::BlockId::Null(); { blockId = CreateBlock()->blockId(); @@ -107,7 +109,7 @@ private: } cpputils::unique_ref StoreDataToBlockAndLoadIt(const cpputils::Data &data) { - blockstore::BlockId blockId = StoreDataToBlockAndGetKey(data); + const blockstore::BlockId blockId = StoreDataToBlockAndGetKey(data); return blockStore->load(blockId).value(); } @@ -122,7 +124,7 @@ private: } cpputils::unique_ref CreateBlockAndLoadIt() { - blockstore::BlockId blockId = CreateBlock()->blockId(); + const blockstore::BlockId blockId = CreateBlock()->blockId(); return blockStore->load(blockId).value(); } diff --git a/test/cpp-utils/assert/assert_debug_test.cpp b/test/cpp-utils/assert/assert_debug_test.cpp index 9e3a2220..c68d73f7 100644 --- a/test/cpp-utils/assert/assert_debug_test.cpp +++ b/test/cpp-utils/assert/assert_debug_test.cpp @@ -22,7 +22,7 @@ TEST(AssertTest_DebugBuild, DiesIfFalse) { } TEST(AssertTest_DebugBuild, whenDisablingAbort_thenThrowsIfFalse) { - cpputils::_assert::DisableAbortOnFailedAssertionRAII _disableAbort; + const cpputils::_assert::DisableAbortOnFailedAssertionRAII _disableAbort; EXPECT_THROW( ASSERT(false, "bla"), cpputils::AssertFailed diff --git a/test/cpp-utils/assert/assert_release_test.cpp b/test/cpp-utils/assert/assert_release_test.cpp index 5dd73824..779b3754 100644 --- a/test/cpp-utils/assert/assert_release_test.cpp +++ b/test/cpp-utils/assert/assert_release_test.cpp @@ -30,7 +30,7 @@ TEST(AssertTest_ReleaseBuild, AssertMessage) { ASSERT(2==5, "my message"); FAIL(); } catch (const cpputils::AssertFailed &e) { - std::string msg = e.what(); + const std::string msg = e.what(); // For some reason, the following doesn't seem to work in MSVC. Possibly because of the multiline string? /*EXPECT_THAT(e.what(), MatchesRegex( R"(Assertion \[2==5\] failed in .*assert_release_test.cpp:27: my message)" diff --git a/test/cpp-utils/assert/backtrace_test.cpp b/test/cpp-utils/assert/backtrace_test.cpp index 2b385bb6..f4d7b579 100644 --- a/test/cpp-utils/assert/backtrace_test.cpp +++ b/test/cpp-utils/assert/backtrace_test.cpp @@ -31,7 +31,7 @@ namespace TEST(BacktraceTest, ContainsTopLevelLine) { - string backtrace = cpputils::backtrace(); + const string backtrace = cpputils::backtrace(); EXPECT_THAT(backtrace, HasSubstr("BacktraceTest")); EXPECT_THAT(backtrace, HasSubstr("ContainsTopLevelLine")); } @@ -103,7 +103,7 @@ TEST(BacktraceTest, DoesntCrashOnCaughtException) #if !(defined(_MSC_VER) && defined(NDEBUG)) TEST(BacktraceTest, ContainsBacktrace) { - string backtrace = cpputils::backtrace(); + const string backtrace = cpputils::backtrace(); #if defined(_MSC_VER) EXPECT_THAT(backtrace, HasSubstr("testing::Test::Run")); #else @@ -111,8 +111,8 @@ TEST(BacktraceTest, ContainsBacktrace) #endif } -#if !(defined(__clang__) && defined(NDEBUG)) -// TODO Can we also make this work on clang in Release mode? +#if !(defined(__clang__)) +// TODO Can we also make this work on clang? TEST(BacktraceTest, ShowBacktraceOnNullptrAccess) { auto output = call_process_exiting_with_nullptr_violation(); diff --git a/test/cpp-utils/assert/exit_signal.cpp b/test/cpp-utils/assert/exit_signal.cpp index cedc9a8d..b29f888f 100644 --- a/test/cpp-utils/assert/exit_signal.cpp +++ b/test/cpp-utils/assert/exit_signal.cpp @@ -18,8 +18,11 @@ void handle_exit_signal(char **argv) { DWORD code = std::atoll(argv[2]); ::RaiseException(code, EXCEPTION_NONCONTINUABLE, 0, NULL); #else - int code = static_cast(std::strtol(argv[2], nullptr, 10)); - ::raise(code); + const int code = static_cast(std::strtol(argv[2], nullptr, 10)); + const int success = ::raise(code); + if (success != 0) { + throw std::runtime_error("Failed to raise signal"); + } #endif } } diff --git a/test/cpp-utils/crypto/hash/HashTest.cpp b/test/cpp-utils/crypto/hash/HashTest.cpp index 20dcee7a..89ee0cd1 100644 --- a/test/cpp-utils/crypto/hash/HashTest.cpp +++ b/test/cpp-utils/crypto/hash/HashTest.cpp @@ -11,35 +11,35 @@ TEST(HashTest, generateSalt_isIndeterministic) { } TEST(HashTest, hash_setsSaltCorrectly) { - Salt salt = generateSalt(); - Data data = DataFixture::generate(1024); + const Salt salt = generateSalt(); + const Data data = DataFixture::generate(1024); EXPECT_EQ(salt, hash(data, salt).salt); } TEST(HashTest, hash_isDeterministicWithSameDataSameSalt) { - Salt salt = generateSalt(); - Data data = DataFixture::generate(1024); + const Salt salt = generateSalt(); + const Data data = DataFixture::generate(1024); EXPECT_EQ(hash(data, salt).digest, hash(data, salt).digest); } TEST(HashTest, hash_isIndeterministicWithSameDataDifferentSalt) { - Salt salt1 = generateSalt(); - Salt salt2 = generateSalt(); - Data data = DataFixture::generate(1024); + const Salt salt1 = generateSalt(); + const Salt salt2 = generateSalt(); + const Data data = DataFixture::generate(1024); EXPECT_NE(hash(data, salt1).digest, hash(data, salt2).digest); } TEST(HashTest, hash_isIndeterministicWithDifferentDataSameSalt) { - Salt salt = generateSalt(); - Data data1 = DataFixture::generate(1024, 1); - Data data2 = DataFixture::generate(1024, 2); + const Salt salt = generateSalt(); + const Data data1 = DataFixture::generate(1024, 1); + const Data data2 = DataFixture::generate(1024, 2); EXPECT_NE(hash(data1, salt).digest, hash(data2, salt).digest); } TEST(HashTest, hash_isIndeterministicWithDifferentDataDifferentSalt) { - Salt salt1 = generateSalt(); - Salt salt2 = generateSalt(); - Data data1 = DataFixture::generate(1024, 1); - Data data2 = DataFixture::generate(1024, 2); + const Salt salt1 = generateSalt(); + const Salt salt2 = generateSalt(); + const Data data1 = DataFixture::generate(1024, 1); + const Data data2 = DataFixture::generate(1024, 2); EXPECT_NE(hash(data1, salt1).digest, hash(data2, salt2).digest); } diff --git a/test/cpp-utils/crypto/kdf/SCryptParametersTest.cpp b/test/cpp-utils/crypto/kdf/SCryptParametersTest.cpp index e4353593..3e299e0b 100644 --- a/test/cpp-utils/crypto/kdf/SCryptParametersTest.cpp +++ b/test/cpp-utils/crypto/kdf/SCryptParametersTest.cpp @@ -8,76 +8,76 @@ using namespace cpputils; class SCryptParametersTest : public ::testing::Test { public: SCryptParameters SaveAndLoad(const SCryptParameters &source) { - Data serialized = source.serialize(); + const Data serialized = source.serialize(); return SCryptParameters::deserialize(serialized); } }; TEST_F(SCryptParametersTest, Salt) { - SCryptParameters cfg(DataFixture::generate(32), 0, 0, 0); + const SCryptParameters cfg(DataFixture::generate(32), 0, 0, 0); EXPECT_EQ(DataFixture::generate(32), cfg.salt()); } TEST_F(SCryptParametersTest, Salt_Move) { SCryptParameters cfg(DataFixture::generate(32), 0, 0, 0); - SCryptParameters moved = std::move(cfg); + const SCryptParameters moved = std::move(cfg); EXPECT_EQ(DataFixture::generate(32), moved.salt()); } TEST_F(SCryptParametersTest, Salt_SaveAndLoad) { - SCryptParameters cfg(DataFixture::generate(32), 0, 0, 0); - SCryptParameters loaded = SaveAndLoad(cfg); + const SCryptParameters cfg(DataFixture::generate(32), 0, 0, 0); + const SCryptParameters loaded = SaveAndLoad(cfg); EXPECT_EQ(DataFixture::generate(32), loaded.salt()); } TEST_F(SCryptParametersTest, N) { - SCryptParameters cfg(Data(0), 1024, 0, 0); + const SCryptParameters cfg(Data(0), 1024, 0, 0); EXPECT_EQ(1024u, cfg.n()); } TEST_F(SCryptParametersTest, N_Move) { SCryptParameters cfg(Data(0), 1024, 0, 0); - SCryptParameters moved = std::move(cfg); + const SCryptParameters moved = std::move(cfg); EXPECT_EQ(1024u, moved.n()); } TEST_F(SCryptParametersTest, N_SaveAndLoad) { - SCryptParameters cfg(Data(0), 1024, 0, 0); - SCryptParameters loaded = SaveAndLoad(cfg); + const SCryptParameters cfg(Data(0), 1024, 0, 0); + const SCryptParameters loaded = SaveAndLoad(cfg); EXPECT_EQ(1024u, loaded.n()); } TEST_F(SCryptParametersTest, r) { - SCryptParameters cfg(Data(0), 0, 8, 0); + const SCryptParameters cfg(Data(0), 0, 8, 0); EXPECT_EQ(8u, cfg.r()); } TEST_F(SCryptParametersTest, r_Move) { SCryptParameters cfg(Data(0), 0, 8, 0); - SCryptParameters moved = std::move(cfg); + const SCryptParameters moved = std::move(cfg); EXPECT_EQ(8u, moved.r()); } TEST_F(SCryptParametersTest, r_SaveAndLoad) { - SCryptParameters cfg(Data(0), 0, 8, 0); - SCryptParameters loaded = SaveAndLoad(cfg); + const SCryptParameters cfg(Data(0), 0, 8, 0); + const SCryptParameters loaded = SaveAndLoad(cfg); EXPECT_EQ(8u, loaded.r()); } TEST_F(SCryptParametersTest, p) { - SCryptParameters cfg(Data(0), 0, 0, 16); + const SCryptParameters cfg(Data(0), 0, 0, 16); EXPECT_EQ(16u, cfg.p()); } TEST_F(SCryptParametersTest, p_Move) { SCryptParameters cfg(Data(0), 0, 0, 16); - SCryptParameters moved = std::move(cfg); + const SCryptParameters moved = std::move(cfg); EXPECT_EQ(16u, moved.p()); } TEST_F(SCryptParametersTest, p_SaveAndLoad) { - SCryptParameters cfg(Data(0), 0, 0, 16); - SCryptParameters loaded = SaveAndLoad(cfg); + const SCryptParameters cfg(Data(0), 0, 0, 16); + const SCryptParameters loaded = SaveAndLoad(cfg); EXPECT_EQ(16u, loaded.p()); } diff --git a/test/cpp-utils/crypto/symmetric/CipherTest.cpp b/test/cpp-utils/crypto/symmetric/CipherTest.cpp index 87470da1..8ea9110b 100644 --- a/test/cpp-utils/crypto/symmetric/CipherTest.cpp +++ b/test/cpp-utils/crypto/symmetric/CipherTest.cpp @@ -17,24 +17,24 @@ public: typename Cipher::EncryptionKey encKey = createKeyFixture(); static typename Cipher::EncryptionKey createKeyFixture(int seed = 0) { - Data data = DataFixture::generate(Cipher::KEYSIZE, seed); + const Data data = DataFixture::generate(Cipher::KEYSIZE, seed); return Cipher::EncryptionKey::FromString(data.ToString()); } void CheckEncryptThenDecryptIsIdentity(const Data &plaintext) { - Data ciphertext = Encrypt(plaintext); - Data decrypted = Decrypt(ciphertext); + const Data ciphertext = Encrypt(plaintext); + const Data decrypted = Decrypt(ciphertext); EXPECT_EQ(plaintext, decrypted); } void CheckEncryptIsIndeterministic(const Data &plaintext) { - Data ciphertext = Encrypt(plaintext); - Data ciphertext2 = Encrypt(plaintext); + const Data ciphertext = Encrypt(plaintext); + const Data ciphertext2 = Encrypt(plaintext); EXPECT_NE(ciphertext, ciphertext2); } void CheckEncryptedSize(const Data &plaintext) { - Data ciphertext = Encrypt(plaintext); + const Data ciphertext = Encrypt(plaintext); EXPECT_EQ(Cipher::ciphertextSize(plaintext.size()), ciphertext.size()); } @@ -73,53 +73,53 @@ TYPED_TEST_P(CipherTest, Size) { TYPED_TEST_P(CipherTest, EncryptThenDecrypt_Zeroes) { for (auto size: SIZES) { - Data plaintext = this->CreateZeroes(size); + const Data plaintext = this->CreateZeroes(size); this->CheckEncryptThenDecryptIsIdentity(plaintext); } } TYPED_TEST_P(CipherTest, EncryptThenDecrypt_Data) { for (auto size: SIZES) { - Data plaintext = this->CreateData(size); + const Data plaintext = this->CreateData(size); this->CheckEncryptThenDecryptIsIdentity(plaintext); } } TYPED_TEST_P(CipherTest, EncryptIsIndeterministic_Zeroes) { for (auto size: SIZES) { - Data plaintext = this->CreateZeroes(size); + const Data plaintext = this->CreateZeroes(size); this->CheckEncryptIsIndeterministic(plaintext); } } TYPED_TEST_P(CipherTest, EncryptIsIndeterministic_Data) { for (auto size: SIZES) { - Data plaintext = this->CreateData(size); + const Data plaintext = this->CreateData(size); this->CheckEncryptIsIndeterministic(plaintext); } } TYPED_TEST_P(CipherTest, EncryptedSize) { for (auto size: SIZES) { - Data plaintext = this->CreateData(size); + const Data plaintext = this->CreateData(size); this->CheckEncryptedSize(plaintext); } } TYPED_TEST_P(CipherTest, TryDecryptDataThatIsTooSmall) { - Data tooSmallCiphertext(TypeParam::ciphertextSize(0) - 1); + const Data tooSmallCiphertext(TypeParam::ciphertextSize(0) - 1); this->ExpectDoesntDecrypt(tooSmallCiphertext); } TYPED_TEST_P(CipherTest, TryDecryptDataThatIsMuchTooSmall_0) { static_assert(TypeParam::ciphertextSize(0) > 0, "If this fails, the test case doesn't make sense."); - Data tooSmallCiphertext(0); + const Data tooSmallCiphertext(0); this->ExpectDoesntDecrypt(tooSmallCiphertext); } TYPED_TEST_P(CipherTest, TryDecryptDataThatIsMuchTooSmall_1) { static_assert(TypeParam::ciphertextSize(0) > 1, "If this fails, the test case doesn't make sense."); - Data tooSmallCiphertext(1); + const Data tooSmallCiphertext(1); this->ExpectDoesntDecrypt(tooSmallCiphertext); } diff --git a/test/cpp-utils/data/DataFixtureTest.cpp b/test/cpp-utils/data/DataFixtureTest.cpp index 0fa60cdc..56277c3d 100644 --- a/test/cpp-utils/data/DataFixtureTest.cpp +++ b/test/cpp-utils/data/DataFixtureTest.cpp @@ -1,5 +1,7 @@ #include +#include + #include "cpp-utils/data/Data.h" #include "cpp-utils/data/DataFixture.h" @@ -12,35 +14,35 @@ class DataFixtureTest: public Test { }; TEST_F(DataFixtureTest, CreateEmptyFixture) { - Data data = DataFixture::generate(0); + const Data data = DataFixture::generate(0); EXPECT_EQ(0u, data.size()); } TEST_F(DataFixtureTest, CreateOneByteFixture) { - Data data = DataFixture::generate(1); + const Data data = DataFixture::generate(1); EXPECT_EQ(1u, data.size()); } TEST_F(DataFixtureTest, CreateLargerFixture) { - Data data = DataFixture::generate(20 * 1024 * 1024); + const Data data = DataFixture::generate(20 * 1024 * 1024); EXPECT_EQ(20u * 1024u * 1024u, data.size()); } TEST_F(DataFixtureTest, FixturesAreDeterministic_DefaultSeed) { - Data data1 = DataFixture::generate(1024 * 1024); - Data data2 = DataFixture::generate(1024 * 1024); + const Data data1 = DataFixture::generate(1024 * 1024); + const Data data2 = DataFixture::generate(1024 * 1024); EXPECT_EQ(data1, data2); } TEST_F(DataFixtureTest, FixturesAreDeterministic_SeedIs5) { - Data data1 = DataFixture::generate(1024 * 1024, 5); - Data data2 = DataFixture::generate(1024 * 1024, 5); + const Data data1 = DataFixture::generate(1024 * 1024, 5); + const Data data2 = DataFixture::generate(1024 * 1024, 5); EXPECT_EQ(data1, data2); } TEST_F(DataFixtureTest, DifferentSeedIsDifferentFixture) { - Data data1 = DataFixture::generate(1024 * 1024, 0); - Data data2 = DataFixture::generate(1024 * 1024, 1); + const Data data1 = DataFixture::generate(1024 * 1024, 0); + const Data data2 = DataFixture::generate(1024 * 1024, 1); EXPECT_NE(data1, data2); } diff --git a/test/cpp-utils/data/DataTest.cpp b/test/cpp-utils/data/DataTest.cpp index 76d1b53d..57d8cce0 100644 --- a/test/cpp-utils/data/DataTest.cpp +++ b/test/cpp-utils/data/DataTest.cpp @@ -4,6 +4,7 @@ #include #include "cpp-utils/tempfile/TempFile.h" +#include #include using ::testing::Test; @@ -69,55 +70,55 @@ TEST_P(DataTestWithSizeParam, ZeroInitializedDataIsDifferentToRandomData) { // Working on a large data area without a crash is a good indicator that we // are actually working on memory that was validly allocated for us. TEST_P(DataTestWithSizeParam, WriteAndCheck) { - Data data = randomData.copy(); + const Data data = randomData.copy(); EXPECT_EQ(randomData, data); } TEST_P(DataTestWithSizeParam, Size) { - Data data(GetParam()); + const Data data(GetParam()); EXPECT_EQ(GetParam(), data.size()); } TEST_P(DataTestWithSizeParam, CheckStoredFile) { - TempFile file; + const TempFile file; randomData.StoreToFile(file.path()); EXPECT_STORED_FILE_DATA_CORRECT(randomData, file.path()); } TEST_P(DataTestWithSizeParam, CheckLoadedData) { - TempFile file; + const TempFile file; StoreData(randomData, file.path()); - Data data = Data::LoadFromFile(file.path()).value(); + const Data data = Data::LoadFromFile(file.path()).value(); EXPECT_EQ(randomData, data); } TEST_P(DataTestWithSizeParam, StoreDoesntChangeData) { - Data data = randomData.copy(); + const Data data = randomData.copy(); - TempFile file; + const TempFile file; data.StoreToFile(file.path()); EXPECT_EQ(randomData, data); } TEST_P(DataTestWithSizeParam, StoreAndLoad) { - TempFile file; + const TempFile file; randomData.StoreToFile(file.path()); - Data loaded_data = Data::LoadFromFile(file.path()).value(); + const Data loaded_data = Data::LoadFromFile(file.path()).value(); EXPECT_EQ(randomData, loaded_data); } TEST_P(DataTestWithSizeParam, Copy) { - Data copy = randomData.copy(); + const Data copy = randomData.copy(); EXPECT_EQ(randomData, copy); } TEST_F(DataTest, ChangingCopyDoesntChangeOriginal) { - Data original = DataFixture::generate(1024); + const Data original = DataFixture::generate(1024); Data copy = original.copy(); serialize(copy.data(), deserialize(copy.data()) + 1); EXPECT_EQ(DataFixture::generate(1024), original); @@ -140,7 +141,7 @@ TEST_F(DataTest, FillModifiedDataWithZeroes) { TEST_F(DataTest, MoveConstructor) { Data original = DataFixture::generate(1024); - Data copy(std::move(original)); + const Data copy(std::move(original)); EXPECT_EQ(DataFixture::generate(1024), copy); EXPECT_EQ(nullptr, original.data()); // NOLINT (intentional use-after-move) EXPECT_EQ(0u, original.size()); // NOLINT (intentional use-after-move) @@ -156,21 +157,21 @@ TEST_F(DataTest, MoveAssignment) { } TEST_F(DataTest, Equality) { - Data data1 = DataFixture::generate(1024); - Data data2 = DataFixture::generate(1024); + const Data data1 = DataFixture::generate(1024); + const Data data2 = DataFixture::generate(1024); EXPECT_TRUE(data1 == data2); EXPECT_FALSE(data1 != data2); } TEST_F(DataTest, Inequality_DifferentSize) { - Data data1 = DataFixture::generate(1024); - Data data2 = DataFixture::generate(1023); + const Data data1 = DataFixture::generate(1024); + const Data data2 = DataFixture::generate(1023); EXPECT_FALSE(data1 == data2); EXPECT_TRUE(data1 != data2); } TEST_F(DataTest, Inequality_DifferentFirstByte) { - Data data1 = DataFixture::generate(1024); + const Data data1 = DataFixture::generate(1024); Data data2 = DataFixture::generate(1024); serialize(data2.data(), deserialize(data2.data()) + 1); EXPECT_FALSE(data1 == data2); @@ -178,7 +179,7 @@ TEST_F(DataTest, Inequality_DifferentFirstByte) { } TEST_F(DataTest, Inequality_DifferentMiddleByte) { - Data data1 = DataFixture::generate(1024); + const Data data1 = DataFixture::generate(1024); Data data2 = DataFixture::generate(1024); serialize(data2.dataOffset(500), deserialize(data2.dataOffset(500)) + 1); EXPECT_FALSE(data1 == data2); @@ -186,7 +187,7 @@ TEST_F(DataTest, Inequality_DifferentMiddleByte) { } TEST_F(DataTest, Inequality_DifferentLastByte) { - Data data1 = DataFixture::generate(1024); + const Data data1 = DataFixture::generate(1024); Data data2 = DataFixture::generate(1024); serialize(data2.dataOffset(1023), deserialize(data2.dataOffset(1023)) + 1); EXPECT_FALSE(data1 == data2); @@ -196,8 +197,8 @@ TEST_F(DataTest, Inequality_DifferentLastByte) { #ifdef __x86_64__ TEST_F(DataTest, LargesizeSize) { //Needs 64bit for representation. This value isn't in the size param list, because the list is also used for read/write checks. - uint64_t size = static_cast(4.5L*1024*1024*1024); - Data data(size); + const uint64_t size = static_cast(4.5L*1024*1024*1024); + const Data data(size); EXPECT_EQ(size, data.size()); } #else @@ -209,7 +210,7 @@ TEST_F(DataTest, LargesizeSize) { #endif TEST_F(DataTest, LoadingNonexistingFile) { - TempFile file(false); // Pass false to constructor, so the tempfile is not created + const TempFile file(false); // Pass false to constructor, so the tempfile is not created EXPECT_FALSE(Data::LoadFromFile(file.path())); } @@ -217,13 +218,13 @@ class DataTestWithStringParam: public DataTest, public WithParamInterface(5, std::move(allocator)); - Data data2 = std::move(*data); + const Data data2 = std::move(*data); data.reset(); EXPECT_CALL(*allocator_ptr, free(&ptr_target, 5)).Times(1); diff --git a/test/cpp-utils/data/FixedSizeDataTest.cpp b/test/cpp-utils/data/FixedSizeDataTest.cpp index b016a39a..17f7dc13 100644 --- a/test/cpp-utils/data/FixedSizeDataTest.cpp +++ b/test/cpp-utils/data/FixedSizeDataTest.cpp @@ -34,32 +34,32 @@ public: constexpr size_t FixedSizeDataTest::SIZE; TEST_F(FixedSizeDataTest, EqualsTrue) { - FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); - FixedSizeData DATA1_2 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData DATA1_2 = FixedSizeData::FromString(DATA1_AS_STRING); EXPECT_TRUE(DATA1_1 == DATA1_2); EXPECT_TRUE(DATA1_2 == DATA1_1); } TEST_F(FixedSizeDataTest, EqualsFalse) { - FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); - FixedSizeData DATA2_1 = FixedSizeData::FromString(DATA2_AS_STRING); + const FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData DATA2_1 = FixedSizeData::FromString(DATA2_AS_STRING); EXPECT_FALSE(DATA1_1 == DATA2_1); EXPECT_FALSE(DATA2_1 == DATA1_1); } TEST_F(FixedSizeDataTest, NotEqualsFalse) { - FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); - FixedSizeData DATA1_2 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData DATA1_2 = FixedSizeData::FromString(DATA1_AS_STRING); EXPECT_FALSE(DATA1_1 != DATA1_2); EXPECT_FALSE(DATA1_2 != DATA1_1); } TEST_F(FixedSizeDataTest, NotEqualsTrue) { - FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); - FixedSizeData DATA2_1 = FixedSizeData::FromString(DATA2_AS_STRING); + const FixedSizeData DATA1_1 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData DATA2_1 = FixedSizeData::FromString(DATA2_AS_STRING); EXPECT_TRUE(DATA1_1 != DATA2_1); EXPECT_TRUE(DATA2_1 != DATA1_1); @@ -69,13 +69,13 @@ class FixedSizeDataTestWithStringParam: public FixedSizeDataTest, public WithPar INSTANTIATE_TEST_SUITE_P(FixedSizeDataTestWithStringParam, FixedSizeDataTestWithStringParam, Values("2898B4B8A13CA63CBE0F0278CCE465DB", "6FFEBAD90C0DAA2B79628F0627CE9841")); TEST_P(FixedSizeDataTestWithStringParam, FromAndToString) { - FixedSizeData data = FixedSizeData::FromString(GetParam()); + const FixedSizeData data = FixedSizeData::FromString(GetParam()); EXPECT_EQ(GetParam(), data.ToString()); } TEST_P(FixedSizeDataTestWithStringParam, ToAndFromString) { - FixedSizeData data = FixedSizeData::FromString(GetParam()); - FixedSizeData data2 = FixedSizeData::FromString(data.ToString()); + const FixedSizeData data = FixedSizeData::FromString(GetParam()); + const FixedSizeData data2 = FixedSizeData::FromString(data.ToString()); EXPECT_EQ(data, data2); } @@ -89,22 +89,22 @@ const Data FixedSizeDataTestWithBinaryParam::VALUE2(DataFixture::generate(SIZE, INSTANTIATE_TEST_SUITE_P(FixedSizeDataTestWithBinaryParam, FixedSizeDataTestWithBinaryParam, Values(&FixedSizeDataTestWithBinaryParam::VALUE1, &FixedSizeDataTestWithBinaryParam::VALUE2)); TEST_P(FixedSizeDataTestWithBinaryParam, FromBinary) { - FixedSizeData data = FixedSizeData::FromBinary(GetParam()->data()); + const FixedSizeData data = FixedSizeData::FromBinary(GetParam()->data()); EXPECT_DATA_EQ(*GetParam(), data); } TEST_P(FixedSizeDataTestWithBinaryParam, FromAndToBinary) { - FixedSizeData data = FixedSizeData::FromBinary(GetParam()->data()); + const FixedSizeData data = FixedSizeData::FromBinary(GetParam()->data()); Data output(FixedSizeData::BINARY_LENGTH); data.ToBinary(output.data()); EXPECT_EQ(*GetParam(), output); } TEST_P(FixedSizeDataTestWithBinaryParam, ToAndFromBinary) { - FixedSizeData data = FixedSizeData::FromBinary(GetParam()->data()); + const FixedSizeData data = FixedSizeData::FromBinary(GetParam()->data()); Data stored(FixedSizeData::BINARY_LENGTH); data.ToBinary(stored.data()); - FixedSizeData loaded = FixedSizeData::FromBinary(stored.data()); + const FixedSizeData loaded = FixedSizeData::FromBinary(stored.data()); EXPECT_EQ(data, loaded); } @@ -112,7 +112,7 @@ class FixedSizeDataTestWithParam: public FixedSizeDataTest, public WithParamInte INSTANTIATE_TEST_SUITE_P(FixedSizeDataTestWithParam, FixedSizeDataTestWithParam, Values(FixedSizeData::FromString("2898B4B8A13CA63CBE0F0278CCE465DB"), FixedSizeData::FromString("6FFEBAD90C0DAA2B79628F0627CE9841"))); TEST_P(FixedSizeDataTestWithParam, CopyConstructor) { - FixedSizeData copy(GetParam()); + const FixedSizeData copy(GetParam()); EXPECT_EQ(GetParam(), copy); } @@ -141,8 +141,8 @@ TEST_P(FixedSizeDataTestWithParam, Drop_One) { } TEST_P(FixedSizeDataTestWithParam, Take_Nothing) { - FixedSizeData source(GetParam()); - FixedSizeData<0> taken = source.take<0>(); + const FixedSizeData source(GetParam()); + const FixedSizeData<0> taken = source.take<0>(); (void)taken; // silence unused variable warning } @@ -159,14 +159,14 @@ TEST_P(FixedSizeDataTestWithParam, Take_All) { } TEST_P(FixedSizeDataTestWithParam, Drop_All) { - FixedSizeData source(GetParam()); - FixedSizeData<0> taken = source.drop(); + const FixedSizeData source(GetParam()); + const FixedSizeData<0> taken = source.drop(); (void)taken; // silence unused variable warning } TEST_F(FixedSizeDataTest, CopyConstructorDoesntChangeSource) { - FixedSizeData data1 = FixedSizeData::FromString(DATA1_AS_STRING); - FixedSizeData data2(data1); + const FixedSizeData data1 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData data2(data1); EXPECT_EQ(DATA1_AS_STRING, data1.ToString()); (void)data2; // silence unused variable warning } @@ -179,7 +179,7 @@ TEST_P(FixedSizeDataTestWithParam, IsEqualAfterAssignment1) { } TEST_F(FixedSizeDataTest, AssignmentDoesntChangeSource) { - FixedSizeData data1 = FixedSizeData::FromString(DATA1_AS_STRING); + const FixedSizeData data1 = FixedSizeData::FromString(DATA1_AS_STRING); FixedSizeData data2 = FixedSizeData::FromString(DATA2_AS_STRING); data2 = data1; EXPECT_EQ(DATA1_AS_STRING, data1.ToString()); diff --git a/test/cpp-utils/data/SerializationHelperTest.cpp b/test/cpp-utils/data/SerializationHelperTest.cpp index e252ee5f..2fc8ae57 100644 --- a/test/cpp-utils/data/SerializationHelperTest.cpp +++ b/test/cpp-utils/data/SerializationHelperTest.cpp @@ -193,7 +193,7 @@ static_assert(sizeof(OneByteStruct) == 1, ""); TEST(SerializationHelperTest, onebytestruct) { Data data(1); - OneByteStruct fixture {5}; + const OneByteStruct fixture {5}; serialize(data.data(), fixture); EXPECT_EQ(fixture.v, deserialize(data.data()).v); } diff --git a/test/cpp-utils/either_test.cpp b/test/cpp-utils/either_test.cpp index 4be62014..b724603b 100644 --- a/test/cpp-utils/either_test.cpp +++ b/test/cpp-utils/either_test.cpp @@ -284,7 +284,7 @@ TEST(EitherTest, givenMultiParamMakeRight) { TEST(EitherTest, givenLeftCopyConstructedFromValue_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - string a = "4"; + const string a = "4"; either b(a); test(b); } @@ -297,7 +297,7 @@ TEST(EitherTest, givenLeftCopyConstructedFromValue_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { string a = "4"; - either b(a); + const either b(a); test(a); } }, @@ -308,7 +308,7 @@ TEST(EitherTest, givenLeftCopyConstructedFromValue_thenOldIsCorrect) { TEST(EitherTest, givenRightCopyConstructedFromValue_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - string a = "4"; + const string a = "4"; either b(a); test(b); } @@ -321,7 +321,7 @@ TEST(EitherTest, givenRightCopyConstructedFromValue_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { string a = "4"; - either b(a); + const either b(a); test(a); } }, @@ -345,7 +345,7 @@ TEST(EitherTest, givenLeftMoveConstructedFromValue_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { MovableOnly a(3); - either b(std::move(a)); + const either b(std::move(a)); test(a); // NOLINT(bugprone-use-after-move) } }, @@ -369,7 +369,7 @@ TEST(EitherTest, givenRightMoveConstructedFromValue_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { MovableOnly a(3); - either b(std::move(a)); + const either b(std::move(a)); test(a); // NOLINT(bugprone-use-after-move) } }, @@ -380,12 +380,12 @@ TEST(EitherTest, givenRightMoveConstructedFromValue_thenOldIsCorrect) { TEST(EitherTest, givenLeftCopyAssignedFromValue_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - string a = "4"; + const string a = "4"; either b(2); b = a; test(b); }, [] (const auto& test) { - string a = "4"; + const string a = "4"; either b("2"); b = a; test(b); @@ -416,12 +416,12 @@ TEST(EitherTest, givenLeftCopyAssignedFromValue_thenOldIsCorrect) { TEST(EitherTest, givenRightCopyAssignedFromValue_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - string a = "4"; + const string a = "4"; either b(2); b = a; test(b); }, [] (const auto& test) { - string a = "4"; + const string a = "4"; either b("2"); b = a; test(b); @@ -524,7 +524,7 @@ TEST(EitherTest, givenRightMoveAssignedFromValue_thenOldIsCorrect) { TEST(EitherTest, givenLeftCopyConstructed_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a("4"); + const either a("4"); either b(a); test(b); } @@ -537,7 +537,7 @@ TEST(EitherTest, givenLeftCopyConstructed_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a("4"); - either b(a); + const either b(a); test(a); } }, @@ -548,7 +548,7 @@ TEST(EitherTest, givenLeftCopyConstructed_thenOldIsCorrect) { TEST(EitherTest, givenLeftCopyConstructed_withSameType_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a = make_left("4"); + const either a = make_left("4"); either b(a); test(b); } @@ -561,7 +561,7 @@ TEST(EitherTest, givenLeftCopyConstructed_withSameType_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a = make_left("4"); - either b(a); + const either b(a); test(a); } }, @@ -572,7 +572,7 @@ TEST(EitherTest, givenLeftCopyConstructed_withSameType_thenOldIsCorrect) { TEST(EitherTest, givenRightCopyConstructed_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a("4"); + const either a("4"); either b(a); test(b); } @@ -586,7 +586,7 @@ TEST(EitherTest, givenRightCopyConstructed_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a("4"); - either b(a); + const either b(a); test(a); } }, @@ -597,7 +597,7 @@ TEST(EitherTest, givenRightCopyConstructed_thenOldIsCorrect) { TEST(EitherTest, givenRightCopyConstructed_withSameType_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a = make_right("4"); + const either a = make_right("4"); either b(a); test(b); } @@ -611,7 +611,7 @@ TEST(EitherTest, givenRightCopyConstructed_withSameType_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a = make_right("4"); - either b(a); + const either b(a); test(a); } }, @@ -635,7 +635,7 @@ TEST(EitherTest, givenLeftMoveConstructed_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a(MovableOnly(3)); - either b(std::move(a)); + const either b(std::move(a)); test(a); // NOLINT(bugprone-use-after-move) } }, @@ -659,7 +659,7 @@ TEST(EitherTest, givenLeftMoveConstructed_withSameType_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a = make_left(MovableOnly(3)); - either b(std::move(a)); + const either b(std::move(a)); test(a); // NOLINT(bugprone-use-after-move) } }, @@ -683,7 +683,7 @@ TEST(EitherTest, givenRightMoveConstructed_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a(MovableOnly(3)); - either b(std::move(a)); + const either b(std::move(a)); test(a); // NOLINT(bugprone-use-after-move) } }, @@ -707,7 +707,7 @@ TEST(EitherTest, givenRightMoveConstructed_withSameType_thenOldIsCorrect) { test_with_matrix({ [] (const auto& test) { either a = make_right(MovableOnly(3)); - either b(std::move(a)); + const either b(std::move(a)); test(a); // NOLINT(bugprone-use-after-move) } }, @@ -718,12 +718,12 @@ TEST(EitherTest, givenRightMoveConstructed_withSameType_thenOldIsCorrect) { TEST(EitherTest, givenLeftCopyAssigned_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a("4"); + const either a("4"); either b(2); b = a; test(b); }, [] (const auto& test) { - either a("4"); + const either a("4"); either b("2"); b = a; test(b); @@ -754,12 +754,12 @@ TEST(EitherTest, givenLeftCopyAssigned_thenOldIsCorrect) { TEST(EitherTest, givenLeftCopyAssigned_withSameType_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a = make_left("4"); + const either a = make_left("4"); either b = make_right("2"); b = a; test(b); }, [] (const auto& test) { - either a = make_left("4"); + const either a = make_left("4"); either b = make_left("2"); b = a; test(b); @@ -790,12 +790,12 @@ TEST(EitherTest, givenLeftCopyAssigned_withSameType_thenOldIsCorrect) { TEST(EitherTest, givenRightCopyAssigned_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a("4"); + const either a("4"); either b(2); b = a; test(b); }, [] (const auto& test) { - either a("4"); + const either a("4"); either b("2"); b = a; test(b); @@ -826,12 +826,12 @@ TEST(EitherTest, givenRightCopyAssigned_thenOldIsCorrect) { TEST(EitherTest, givenRightCopyAssigned_withSameType_thenNewIsCorrect) { test_with_matrix({ [] (const auto& test) { - either a = make_right("4"); + const either a = make_right("4"); either b = make_left("2"); b = a; test(b); }, [] (const auto& test) { - either a = make_right("4"); + const either a = make_right("4"); either b = make_right("2"); b = a; test(b); @@ -1058,39 +1058,39 @@ TEST(EitherTest, canEmplaceConstructRight) { } TEST(EitherTest, givenEqualLefts_thenAreEqual) { - either a("3"); - either b("3"); + const either a("3"); + const either b("3"); EXPECT_TRUE(a == b); } TEST(EitherTest, givenEqualLefts_thenAreNotUnequal) { - either a("3"); - either b("3"); + const either a("3"); + const either b("3"); EXPECT_FALSE(a != b); } TEST(EitherTest, givenEqualRights_thenAreEqual) { - either a(3); - either b(3); + const either a(3); + const either b(3); EXPECT_TRUE(a == b); } TEST(EitherTest, givenEqualRights_thenAreNotUnequal) { - either a(3); - either b(3); + const either a(3); + const either b(3); EXPECT_FALSE(a != b); } TEST(EitherTest, givenLeftAndRight_thenAreNotEqual) { - either a("3"); - either b(3); + const either a("3"); + const either b(3); EXPECT_FALSE(a == b); EXPECT_FALSE(b == a); } TEST(EitherTest, givenLeftAndRight_thenAreUnequal) { - either a("3"); - either b(3); + const either a("3"); + const either b(3); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); } @@ -1108,15 +1108,15 @@ TEST(EitherTest, OutputRight) { } TEST(EitherTest, givenLeftAndRightWithSameType_thenAreNotEqual) { - either a = make_left("3"); - either b = make_right("3"); + const either a = make_left("3"); + const either b = make_right("3"); EXPECT_FALSE(a == b); EXPECT_FALSE(b == a); } TEST(EitherTest, givenLeftAndRightWithSameType_thenAreUnequal) { - either a = make_left("3"); - either b = make_right("3"); + const either a = make_left("3"); + const either b = make_right("3"); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); } @@ -1165,34 +1165,34 @@ TEST(EitherTest_Destructor, LeftDestructorIsCalled) { DestructorCallback destructorCallback; destructorCallback.EXPECT_CALLED(2); //Once for the temp object, once when the either class destructs - ClassWithDestructorCallback temp(&destructorCallback); - either var = temp; + const ClassWithDestructorCallback temp(&destructorCallback); + const either var = temp; } TEST(EitherTest_Destructor, RightDestructorIsCalled) { DestructorCallback destructorCallback; destructorCallback.EXPECT_CALLED(2); //Once for the temp object, once when the either class destructs - ClassWithDestructorCallback temp(&destructorCallback); - either var = temp; + const ClassWithDestructorCallback temp(&destructorCallback); + const either var = temp; } TEST(EitherTest_Destructor, LeftDestructorIsCalledAfterCopying) { DestructorCallback destructorCallback; destructorCallback.EXPECT_CALLED(3); //Once for the temp object, once for var1 and once for var2 - ClassWithDestructorCallback temp(&destructorCallback); - either var1 = temp; - either var2 = var1; + const ClassWithDestructorCallback temp(&destructorCallback); + const either var1 = temp; + const either var2 = var1; } TEST(EitherTest_Destructor, RightDestructorIsCalledAfterCopying) { DestructorCallback destructorCallback; destructorCallback.EXPECT_CALLED(3); //Once for the temp object, once for var1 and once for var2 - ClassWithDestructorCallback temp(&destructorCallback); - either var1 = temp; - either var2 = var1; + const ClassWithDestructorCallback temp(&destructorCallback); + const either var1 = temp; + const either var2 = var1; } TEST(EitherTest_Destructor, LeftDestructorIsCalledAfterMoving) { @@ -1201,7 +1201,7 @@ TEST(EitherTest_Destructor, LeftDestructorIsCalledAfterMoving) { OnlyMoveableClassWithDestructorCallback temp(&destructorCallback); either var1 = std::move(temp); - either var2 = std::move(var1); + const either var2 = std::move(var1); } TEST(EitherTest_Destructor, RightDestructorIsCalledAfterMoving) { @@ -1210,7 +1210,7 @@ TEST(EitherTest_Destructor, RightDestructorIsCalledAfterMoving) { OnlyMoveableClassWithDestructorCallback temp(&destructorCallback); either var1 = std::move(temp); - either var2 = std::move(var1); + const either var2 = std::move(var1); } TEST(EitherTest_Destructor, LeftDestructorIsCalledAfterAssignment) { @@ -1219,10 +1219,10 @@ TEST(EitherTest_Destructor, LeftDestructorIsCalledAfterAssignment) { destructorCallback1.EXPECT_CALLED(2); //Once for the temp1 object, once at the assignment destructorCallback2.EXPECT_CALLED(3); //Once for the temp2 object, once in destructor of var2, once in destructor of var1 - ClassWithDestructorCallback temp1(&destructorCallback1); + const ClassWithDestructorCallback temp1(&destructorCallback1); either var1 = temp1; - ClassWithDestructorCallback temp2(&destructorCallback2); - either var2 = temp2; + const ClassWithDestructorCallback temp2(&destructorCallback2); + const either var2 = temp2; var1 = var2; } @@ -1232,10 +1232,10 @@ TEST(EitherTest_Destructor, RightDestructorIsCalledAfterAssignment) { destructorCallback1.EXPECT_CALLED(2); //Once for the temp1 object, once at the assignment destructorCallback2.EXPECT_CALLED(3); //Once for the temp2 object, once in destructor of var2, once in destructor of var1 - ClassWithDestructorCallback temp1(&destructorCallback1); + const ClassWithDestructorCallback temp1(&destructorCallback1); either var1 = temp1; - ClassWithDestructorCallback temp2(&destructorCallback2); - either var2 = temp2; + const ClassWithDestructorCallback temp2(&destructorCallback2); + const either var2 = temp2; var1 = var2; } diff --git a/test/cpp-utils/io/ConsoleTest.h b/test/cpp-utils/io/ConsoleTest.h index 10a57f49..d3208dc5 100644 --- a/test/cpp-utils/io/ConsoleTest.h +++ b/test/cpp-utils/io/ConsoleTest.h @@ -49,7 +49,7 @@ public: std::string actual; std::getline(_output, actual, delimiter); EXPECT_EQ(expected, actual); - for (char expected_char : expected_after_delimiter) { + for (const char expected_char : expected_after_delimiter) { char actual_char = 0; _output.get(actual_char); EXPECT_EQ(expected_char, actual_char); diff --git a/test/cpp-utils/io/DontEchoStdinToStdoutRAIITest.cpp b/test/cpp-utils/io/DontEchoStdinToStdoutRAIITest.cpp index 75dec5f3..4d6ed79c 100644 --- a/test/cpp-utils/io/DontEchoStdinToStdoutRAIITest.cpp +++ b/test/cpp-utils/io/DontEchoStdinToStdoutRAIITest.cpp @@ -4,5 +4,5 @@ using cpputils::DontEchoStdinToStdoutRAII; TEST(DontEchoStdinToStdoutRAIITest, DoesntCrash) { - DontEchoStdinToStdoutRAII a; + const DontEchoStdinToStdoutRAII a; } diff --git a/test/cpp-utils/logging/LoggingTest.cpp b/test/cpp-utils/logging/LoggingTest.cpp index 3539561b..594584a3 100644 --- a/test/cpp-utils/logging/LoggingTest.cpp +++ b/test/cpp-utils/logging/LoggingTest.cpp @@ -13,7 +13,7 @@ using std::string; #if !defined(_MSC_VER) || NDEBUG TEST_F(LoggingTest, DefaultLoggerIsStderr) { - string output = captureStderr([]{ + const string output = captureStderr([]{ LOG(INFO, "My log message"); cpputils::logging::flush(); }); @@ -24,7 +24,7 @@ TEST_F(LoggingTest, DefaultLoggerIsStderr) { TEST_F(LoggingTest, SetLogger_NewLoggerIsUsed) { setLogger(spdlog::stderr_logger_mt("MyTestLog2")); - string output = captureStderr([]{ + const string output = captureStderr([]{ LOG(INFO, "My log message"); cpputils::logging::flush(); }); @@ -46,7 +46,7 @@ TEST_F(LoggingTest, SetNonStderrLogger_LogsToNewLogger) { TEST_F(LoggingTest, SetNonStderrLogger_DoesNotLogToStderr) { setLogger(mockLogger.get()); - string output = captureStderr([] { + const string output = captureStderr([] { logger()->info("My log message"); cpputils::logging::flush(); }); @@ -118,7 +118,7 @@ TEST_F(LoggingTest, MessageIsConstChar) { TEST_F(LoggingTest, MessageIsString) { setLogger(mockLogger.get()); - string msg = "My log message"; + const string msg = "My log message"; LOG(INFO, msg); cpputils::logging::flush(); // For some reason, the following doesn't seem to work in MSVC. Possibly because of the multiline string? @@ -128,7 +128,7 @@ TEST_F(LoggingTest, MessageIsString) { TEST_F(LoggingTest, FormatWithStringPlaceholder) { setLogger(mockLogger.get()); - string str = "placeholder"; + const string str = "placeholder"; LOG(INFO, "My log message: {}", str); cpputils::logging::flush(); // For some reason, the following doesn't seem to work in MSVC. Possibly because of the multiline string? diff --git a/test/cpp-utils/logging/testutils/LoggingTest.h b/test/cpp-utils/logging/testutils/LoggingTest.h index b102f234..f30b3630 100644 --- a/test/cpp-utils/logging/testutils/LoggingTest.h +++ b/test/cpp-utils/logging/testutils/LoggingTest.h @@ -40,7 +40,7 @@ public: return testing::internal::GetCapturedStderr(); } - ~LoggingTest() { + ~LoggingTest() override { cpputils::logging::reset(); } diff --git a/test/cpp-utils/network/FakeHttpClientTest.cpp b/test/cpp-utils/network/FakeHttpClientTest.cpp index 922578c5..98f561c6 100644 --- a/test/cpp-utils/network/FakeHttpClientTest.cpp +++ b/test/cpp-utils/network/FakeHttpClientTest.cpp @@ -2,7 +2,6 @@ #include "cpp-utils/network/FakeHttpClient.h" #include "cpp-utils/pointer/unique_ref_boost_optional_gtest_workaround.h" -using boost::none; using namespace cpputils; diff --git a/test/cpp-utils/pointer/cast_test.cpp b/test/cpp-utils/pointer/cast_test.cpp index 937c89f0..47eea7b1 100644 --- a/test/cpp-utils/pointer/cast_test.cpp +++ b/test/cpp-utils/pointer/cast_test.cpp @@ -28,7 +28,7 @@ public: Child(const DestructorCallback *childDestructorCallback) : _destructorCallback(childDestructorCallback) { } Child(): Child(nullptr) {} - ~Child() { + ~Child() override { if (_destructorCallback != nullptr) { _destructorCallback->call(); } @@ -44,21 +44,21 @@ class Child2 : public Parent {}; TEST(UniquePtr_DynamicPointerMoveTest, NullPtrParentToChildCast) { unique_ptr source(nullptr); - unique_ptr casted = dynamic_pointer_move(source); + const unique_ptr casted = dynamic_pointer_move(source); EXPECT_EQ(nullptr, source.get()); EXPECT_EQ(nullptr, casted.get()); } TEST(UniquePtr_DynamicPointerMoveTest, NullPtrChildToParentCast) { unique_ptr source(nullptr); - unique_ptr casted = dynamic_pointer_move(source); + const unique_ptr casted = dynamic_pointer_move(source); EXPECT_EQ(nullptr, source.get()); EXPECT_EQ(nullptr, casted.get()); } TEST(UniquePtr_DynamicPointerMoveTest, NullPtrSelfCast) { unique_ptr source(nullptr); - unique_ptr casted = dynamic_pointer_move(source); + const unique_ptr casted = dynamic_pointer_move(source); EXPECT_EQ(nullptr, source.get()); EXPECT_EQ(nullptr, casted.get()); } @@ -66,7 +66,7 @@ TEST(UniquePtr_DynamicPointerMoveTest, NullPtrSelfCast) { TEST(UniqueRef_DynamicPointerMoveTest, ValidParentToChildCast) { Child *obj = new Child(); unique_ref source(nullcheck(unique_ptr(obj)).value()); - unique_ref casted = dynamic_pointer_move(source).value(); + const unique_ref casted = dynamic_pointer_move(source).value(); EXPECT_FALSE(source.is_valid()); // source lost ownership EXPECT_EQ(obj, casted.get()); } @@ -74,7 +74,7 @@ TEST(UniqueRef_DynamicPointerMoveTest, ValidParentToChildCast) { TEST(UniquePtr_DynamicPointerMoveTest, ValidParentToChildCast) { Child *obj = new Child(); unique_ptr source(obj); - unique_ptr casted = dynamic_pointer_move(source); + const unique_ptr casted = dynamic_pointer_move(source); EXPECT_EQ(nullptr, source.get()); // source lost ownership EXPECT_EQ(obj, casted.get()); } @@ -82,7 +82,7 @@ TEST(UniquePtr_DynamicPointerMoveTest, ValidParentToChildCast) { TEST(UniqueRef_DynamicPointerMoveTest, InvalidParentToChildCast1) { Parent *obj = new Parent(); unique_ref source(nullcheck(unique_ptr(obj)).value()); - optional> casted = dynamic_pointer_move(source); + const optional> casted = dynamic_pointer_move(source); EXPECT_EQ(obj, source.get()); // source still has ownership EXPECT_EQ(none, casted); } @@ -90,7 +90,7 @@ TEST(UniqueRef_DynamicPointerMoveTest, InvalidParentToChildCast1) { TEST(UniquePtr_DynamicPointerMoveTest, InvalidParentToChildCast1) { Parent *obj = new Parent(); unique_ptr source(obj); - unique_ptr casted = dynamic_pointer_move(source); + const unique_ptr casted = dynamic_pointer_move(source); EXPECT_EQ(obj, source.get()); // source still has ownership EXPECT_EQ(nullptr, casted.get()); } @@ -98,7 +98,7 @@ TEST(UniquePtr_DynamicPointerMoveTest, InvalidParentToChildCast1) { TEST(UniqueRef_DynamicPointerMoveTest, InvalidParentToChildCast2) { Child2 *obj = new Child2(); unique_ref source(nullcheck(unique_ptr(obj)).value()); - optional> casted = dynamic_pointer_move(source); + const optional> casted = dynamic_pointer_move(source); EXPECT_EQ(obj, source.get()); // source still has ownership EXPECT_EQ(none, casted); } @@ -106,7 +106,7 @@ TEST(UniqueRef_DynamicPointerMoveTest, InvalidParentToChildCast2) { TEST(UniquePtr_DynamicPointerMoveTest, InvalidParentToChildCast2) { Child2 *obj = new Child2(); unique_ptr source(obj); - unique_ptr casted = dynamic_pointer_move(source); + const unique_ptr casted = dynamic_pointer_move(source); EXPECT_EQ(obj, source.get()); // source still has ownership EXPECT_EQ(nullptr, casted.get()); } @@ -114,7 +114,7 @@ TEST(UniquePtr_DynamicPointerMoveTest, InvalidParentToChildCast2) { TEST(UniqueRef_DynamicPointerMoveTest, ChildToParentCast) { Child *obj = new Child(); unique_ref source(nullcheck(unique_ptr(obj)).value()); - unique_ref casted = dynamic_pointer_move(source).value(); + const unique_ref casted = dynamic_pointer_move(source).value(); EXPECT_FALSE(source.is_valid()); // source lost ownership EXPECT_EQ(obj, casted.get()); } @@ -122,7 +122,7 @@ TEST(UniqueRef_DynamicPointerMoveTest, ChildToParentCast) { TEST(UniquePtr_DynamicPointerMoveTest, ChildToParentCast) { Child *obj = new Child(); unique_ptr source(obj); - unique_ptr casted = dynamic_pointer_move(source); + const unique_ptr casted = dynamic_pointer_move(source); EXPECT_EQ(nullptr, source.get()); // source lost ownership EXPECT_EQ(obj, casted.get()); } @@ -155,35 +155,35 @@ public: }; TEST_F(UniqueRef_DynamicPointerMoveDestructorTest, ChildInParentPtr) { - unique_ref parent = createChild(); + const unique_ref parent = createChild(); EXPECT_CHILD_DESTRUCTOR_CALLED(); } TEST_F(UniquePtr_DynamicPointerMoveDestructorTest, ChildInParentPtr) { - unique_ptr parent = createChild(); + const unique_ptr parent = createChild(); EXPECT_CHILD_DESTRUCTOR_CALLED(); } TEST_F(UniqueRef_DynamicPointerMoveDestructorTest, ChildToParentCast) { unique_ref child = createChild(); - unique_ref parent = dynamic_pointer_move(child).value(); + const unique_ref parent = dynamic_pointer_move(child).value(); EXPECT_CHILD_DESTRUCTOR_CALLED(); } TEST_F(UniquePtr_DynamicPointerMoveDestructorTest, ChildToParentCast) { unique_ptr child = createChild(); - unique_ptr parent = dynamic_pointer_move(child); + const unique_ptr parent = dynamic_pointer_move(child); EXPECT_CHILD_DESTRUCTOR_CALLED(); } TEST_F(UniqueRef_DynamicPointerMoveDestructorTest, ParentToChildCast) { unique_ref parent = createChild(); - unique_ref child = dynamic_pointer_move(parent).value(); + const unique_ref child = dynamic_pointer_move(parent).value(); EXPECT_CHILD_DESTRUCTOR_CALLED(); } TEST_F(UniquePtr_DynamicPointerMoveDestructorTest, ParentToChildCast) { unique_ptr parent = createChild(); - unique_ptr child = dynamic_pointer_move(parent); + const unique_ptr child = dynamic_pointer_move(parent); EXPECT_CHILD_DESTRUCTOR_CALLED(); } diff --git a/test/cpp-utils/pointer/optional_ownership_ptr_test.cpp b/test/cpp-utils/pointer/optional_ownership_ptr_test.cpp index 69fcba55..0d266a44 100644 --- a/test/cpp-utils/pointer/optional_ownership_ptr_test.cpp +++ b/test/cpp-utils/pointer/optional_ownership_ptr_test.cpp @@ -60,7 +60,7 @@ TEST_F(OptionalOwnershipPointerTest, TestIsInitializedCorrectly) { TEST_F(OptionalOwnershipPointerTest, DestructsWhenItHasOwnership_UniquePtr) { { - optional_ownership_ptr ptr = WithOwnership(unique_ptr(obj.get())); + const optional_ownership_ptr ptr = WithOwnership(unique_ptr(obj.get())); EXPECT_FALSE(obj.isDestructed()); UNUSED(ptr); } @@ -69,7 +69,7 @@ TEST_F(OptionalOwnershipPointerTest, DestructsWhenItHasOwnership_UniquePtr) { TEST_F(OptionalOwnershipPointerTest, DestructsWhenItHasOwnership_UniqueRef) { { - optional_ownership_ptr ptr = WithOwnership(cpputils::nullcheck(unique_ptr(obj.get())).value()); + const optional_ownership_ptr ptr = WithOwnership(cpputils::nullcheck(unique_ptr(obj.get())).value()); //EXPECT_FALSE(obj.isDestructed()); //UNUSED(ptr); } @@ -88,7 +88,7 @@ TEST_F(OptionalOwnershipPointerTest, DestructsWhenItHasOwnershipAfterAssignment) TEST_F(OptionalOwnershipPointerTest, DoesntDestructWhenItDoesntHaveOwnership) { { - optional_ownership_ptr ptr = WithoutOwnership(obj.get()); + const optional_ownership_ptr ptr = WithoutOwnership(obj.get()); UNUSED(ptr); } EXPECT_FALSE(obj.isDestructed()); @@ -110,16 +110,16 @@ TEST_F(OptionalOwnershipPointerTest, DestructsOnReassignmentWithNull) { } TEST_F(OptionalOwnershipPointerTest, DoesntCrashWhenDestructingNullptr1) { - optional_ownership_ptr ptr = null(); + const optional_ownership_ptr ptr = null(); UNUSED(ptr); } TEST_F(OptionalOwnershipPointerTest, DoesntCrashWhenDestructingNullptrWithoutOwnership) { - optional_ownership_ptr ptr = WithoutOwnership(static_cast(nullptr)); + const optional_ownership_ptr ptr = WithoutOwnership(static_cast(nullptr)); UNUSED(ptr); } TEST_F(OptionalOwnershipPointerTest, DoesntCrashWhenDestructingNullptrWithOwnership) { - optional_ownership_ptr ptr = WithOwnership(unique_ptr(nullptr)); + const optional_ownership_ptr ptr = WithOwnership(unique_ptr(nullptr)); UNUSED(ptr); } diff --git a/test/cpp-utils/pointer/unique_ref_test.cpp b/test/cpp-utils/pointer/unique_ref_test.cpp index 27459bc8..8e0889d5 100644 --- a/test/cpp-utils/pointer/unique_ref_test.cpp +++ b/test/cpp-utils/pointer/unique_ref_test.cpp @@ -36,12 +36,12 @@ static_assert(std::is_same::element_ty static_assert(std::is_same::deleter_type>::value, "unique_ref::deleter_type is wrong"); TEST(MakeUniqueRefTest, Primitive) { - unique_ref var = make_unique_ref(3); + const unique_ref var = make_unique_ref(3); EXPECT_EQ(3, *var); } TEST(MakeUniqueRefTest, ClassWith0Parameters) { - unique_ref var = make_unique_ref(); + const unique_ref var = make_unique_ref(); //Check that the type is correct EXPECT_EQ(var.get(), dynamic_cast(var.get())); } @@ -65,12 +65,12 @@ TEST(MakeUniqueRefTest, TypeIsAutoDeductible) { } TEST(MakeUniqueRefTest, CanAssignToUniquePtr) { - std::unique_ptr var = make_unique_ref(2); + const std::unique_ptr var = make_unique_ref(2); EXPECT_EQ(2, *var); } TEST(MakeUniqueRefTest, CanAssignToSharedPtr) { - std::shared_ptr var = make_unique_ref(2); + const std::shared_ptr var = make_unique_ref(2); EXPECT_EQ(2, *var); } @@ -85,17 +85,17 @@ TEST(MakeUniqueRefTest, CanAssignToBaseClassUniquePtr) { } TEST(MakeUniqueRefTest, CanAssignToBaseClassSharedPtr) { - std::shared_ptr var = make_unique_ref(3); + const std::shared_ptr var = make_unique_ref(3); EXPECT_EQ(3, var->v); } TEST(NullcheckTest, givenUniquePtrToInt_withNullptr_whenNullcheckCalled_thenReturnsNone) { - boost::optional> var = nullcheck(std::unique_ptr(nullptr)); + const boost::optional> var = nullcheck(std::unique_ptr(nullptr)); EXPECT_FALSE(static_cast(var)); } TEST(NullcheckTest, givenUniquePtrToObject_withNullptr_whenNullcheckCalled_thenReturnsNone) { - boost::optional> var = nullcheck(std::unique_ptr(nullptr)); + const boost::optional> var = nullcheck(std::unique_ptr(nullptr)); EXPECT_FALSE(static_cast(var)); } @@ -127,12 +127,12 @@ TEST(NullcheckTest, givenUniquePtrToObjectWith2Parameters_withNonNullptr_whenNul TEST(NullcheckTest, givenUniquePtrToInt_withNonNullptr_whenNullcheckCalled_thenCanExtractUniqueRef) { boost::optional> var = nullcheck(std::make_unique(3)); - unique_ref resolved = std::move(var).value(); + const unique_ref resolved = std::move(var).value(); } TEST(NullcheckTest, givenUniquePtrToObject_withNonNullptr_whenNullcheckCalled_thenCanExtractUniqueRef) { boost::optional> var = nullcheck(std::make_unique()); - unique_ref resolved = std::move(var).value(); + const unique_ref resolved = std::move(var).value(); } TEST(NullcheckTest, givenUniquePtrToInt_whenCallingNullcheck_thenTypesCanBeAutoDeduced) { @@ -154,22 +154,22 @@ public: }; TEST_F(UniqueRefTest, givenUniqueRefToInt_whenCallingGet_thenReturnsValue) { - unique_ref obj = make_unique_ref(3); + const unique_ref obj = make_unique_ref(3); EXPECT_EQ(3, *obj.get()); } TEST_F(UniqueRefTest, givenUniqueRefToObject_whenCallingGet_thenReturnsObject) { - unique_ref obj = make_unique_ref(5); + const unique_ref obj = make_unique_ref(5); EXPECT_EQ(5, obj.get()->param); } TEST_F(UniqueRefTest, givenUniqueRefToInt_whenDereferencing_thenReturnsValue) { - unique_ref obj = make_unique_ref(3); + const unique_ref obj = make_unique_ref(3); EXPECT_EQ(3, *obj); } TEST_F(UniqueRefTest, givenUniqueRefToObject_whenDereferencing_thenReturnsObject) { - unique_ref obj = make_unique_ref(5); + const unique_ref obj = make_unique_ref(5); EXPECT_EQ(5, (*obj).param); } @@ -268,13 +268,13 @@ TEST_F(UniqueRefTest, givenUniqueRef_whenMoveAssigningToBaseClassSharedPtr_thenO TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructing_thenPointsToSameObject) { unique_ref obj1 = make_unique_ref(); SomeClass *obj1ptr = obj1.get(); - unique_ref obj2 = std::move(obj1); + const unique_ref obj2 = std::move(obj1); EXPECT_EQ(obj1ptr, obj2.get()); } TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructing_thenOldInstanceInvalid) { unique_ref obj1 = make_unique_ref(); - unique_ref obj2 = std::move(obj1); + const unique_ref obj2 = std::move(obj1); EXPECT_FALSE(obj1.is_valid()); // NOLINT (intentional use-after-move) } @@ -286,20 +286,20 @@ TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToBaseClass_thenPointsT TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToBaseClass_thenOldInstanceInvalid) { unique_ref child = make_unique_ref(3); - unique_ref base = std::move(child); + const unique_ref base = std::move(child); EXPECT_FALSE(child.is_valid()); // NOLINT (intentional use-after-move) } TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToUniquePtr_thenPointsToSameObject) { unique_ref obj1 = make_unique_ref(); SomeClass *obj1ptr = obj1.get(); - std::unique_ptr obj2 = std::move(obj1); + const std::unique_ptr obj2 = std::move(obj1); EXPECT_EQ(obj1ptr, obj2.get()); } TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToUniquePtr_thenOldInstanceInvalid) { unique_ref obj1 = make_unique_ref(); - std::unique_ptr obj2 = std::move(obj1); + const std::unique_ptr obj2 = std::move(obj1); EXPECT_FALSE(obj1.is_valid()); // NOLINT (intentional use-after-move) } @@ -311,32 +311,32 @@ TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToBaseClassUniquePtr_th TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToBaseClassUniquePtr_thenOldInstanceInvalid) { unique_ref child = make_unique_ref(3); - std::unique_ptr base = std::move(child); + const std::unique_ptr base = std::move(child); EXPECT_FALSE(child.is_valid()); // NOLINT (intentional use-after-move) } TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToSharedPtr_thenPointsToSameObject) { unique_ref obj1 = make_unique_ref(); SomeClass *obj1ptr = obj1.get(); - std::shared_ptr obj2 = std::move(obj1); + const std::shared_ptr obj2 = std::move(obj1); EXPECT_EQ(obj1ptr, obj2.get()); } TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToSharedPtr_thenOldInstanceInvalid) { unique_ref obj1 = make_unique_ref(); - std::shared_ptr obj2 = std::move(obj1); + const std::shared_ptr obj2 = std::move(obj1); EXPECT_FALSE(obj1.is_valid()); // NOLINT (intentional use-after-move) } TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToBaseClassSharedPtr_thenPointsToSameObject) { unique_ref child = make_unique_ref(3); - std::shared_ptr base = std::move(child); + const std::shared_ptr base = std::move(child); EXPECT_EQ(3, base->v); } TEST_F(UniqueRefTest, givenUniqueRef_whenMoveConstructingToBaseClassSharedPtr_thenOldInstanceInvalid) { unique_ref child = make_unique_ref(3); - std::shared_ptr base = std::move(child); + const std::shared_ptr base = std::move(child); EXPECT_FALSE(child.is_valid()); // NOLINT (intentional use-after-move) } @@ -368,7 +368,7 @@ TEST_F(UniqueRefTest, SwapWithInvalid) { SomeClass *obj1ptr = obj1.get(); std::swap(obj1, obj2); EXPECT_FALSE(obj1.is_valid()); - EXPECT_TRUE(obj2.is_valid()); + EXPECT_TRUE(obj2.is_valid()); // NOLINT(clang-analyzer-cplusplus.Move) EXPECT_EQ(obj1ptr, obj2.get()); } @@ -378,8 +378,8 @@ TEST_F(UniqueRefTest, SwapInvalidWithInvalid) { makeInvalid(std::move(obj1)); makeInvalid(std::move(obj2)); std::swap(obj1, obj2); - EXPECT_FALSE(obj1.is_valid()); - EXPECT_FALSE(obj2.is_valid()); + EXPECT_FALSE(obj1.is_valid()); // NOLINT(clang-analyzer-cplusplus.Move) + EXPECT_FALSE(obj2.is_valid()); // NOLINT(clang-analyzer-cplusplus.Move) } TEST_F(UniqueRefTest, SwapFromRValue) { @@ -388,7 +388,7 @@ TEST_F(UniqueRefTest, SwapFromRValue) { SomeClass *obj1ptr = obj1.get(); SomeClass *obj2ptr = obj2.get(); std::swap(std::move(obj1), obj2); - EXPECT_EQ(obj2ptr, obj1.get()); // NOLINT (intentional use-after-move) + EXPECT_EQ(obj2ptr, obj1.get()); // NOLINT(clang-analyzer-cplusplus.Move,bugprone-use-after-move) EXPECT_EQ(obj1ptr, obj2.get()); } @@ -508,22 +508,22 @@ TEST_F(UniqueRefTest, Equality_Nullptr) { } TEST_F(UniqueRefTest, Nonequality) { - unique_ref var1 = make_unique_ref(3); - unique_ref var2 = make_unique_ref(3); + const unique_ref var1 = make_unique_ref(3); + const unique_ref var2 = make_unique_ref(3); EXPECT_TRUE(var1 != var2); EXPECT_FALSE(var1 == var2); } TEST_F(UniqueRefTest, Nonequality_NullptrLeft) { unique_ref var1 = make_unique_ref(3); - unique_ref var2 = make_unique_ref(3); + const unique_ref var2 = make_unique_ref(3); makeInvalid(std::move(var1)); EXPECT_TRUE(var1 != var2); // NOLINT (intentional use-after-move) EXPECT_FALSE(var1 == var2); // NOLINT (intentional use-after-move) } TEST_F(UniqueRefTest, Nonequality_NullptrRight) { - unique_ref var1 = make_unique_ref(3); + const unique_ref var1 = make_unique_ref(3); unique_ref var2 = make_unique_ref(3); makeInvalid(std::move(var2)); EXPECT_TRUE(var1 != var2); // NOLINT (intentional use-after-move) @@ -531,20 +531,20 @@ TEST_F(UniqueRefTest, Nonequality_NullptrRight) { } TEST_F(UniqueRefTest, HashIsDifferent) { - unique_ref var1 = make_unique_ref(3); - unique_ref var2 = make_unique_ref(3); + const unique_ref var1 = make_unique_ref(3); + const unique_ref var2 = make_unique_ref(3); EXPECT_NE(std::hash>()(var1), std::hash>()(var2)); } TEST_F(UniqueRefTest, HashIsDifferent_NullptrLeft) { unique_ref var1 = make_unique_ref(3); - unique_ref var2 = make_unique_ref(3); + const unique_ref var2 = make_unique_ref(3); makeInvalid(std::move(var1)); EXPECT_NE(std::hash>()(var1), std::hash>()(var2)); // NOLINT (intentional use-after-move) } TEST_F(UniqueRefTest, HashIsDifferent_NullptrRight) { - unique_ref var1 = make_unique_ref(3); + const unique_ref var1 = make_unique_ref(3); unique_ref var2 = make_unique_ref(3); makeInvalid(std::move(var2)); EXPECT_NE(std::hash>()(var1), std::hash>()(var2)); // NOLINT (intentional use-after-move) @@ -559,20 +559,20 @@ TEST_F(UniqueRefTest, HashIsSame_BothNullptr) { } TEST_F(UniqueRefTest, OneIsLess) { - unique_ref var1 = make_unique_ref(3); - unique_ref var2 = make_unique_ref(3); + const unique_ref var1 = make_unique_ref(3); + const unique_ref var2 = make_unique_ref(3); EXPECT_TRUE(std::less>()(var1, var2) != std::less>()(var2, var1)); } TEST_F(UniqueRefTest, NullptrIsLess1) { unique_ref var1 = make_unique_ref(3); - unique_ref var2 = make_unique_ref(3); + const unique_ref var2 = make_unique_ref(3); makeInvalid(std::move(var1)); EXPECT_TRUE(std::less>()(var1, var2)); // NOLINT (intentional use-after-move) } TEST_F(UniqueRefTest, NullptrIsLess2) { - unique_ref var1 = make_unique_ref(3); + const unique_ref var1 = make_unique_ref(3); unique_ref var2 = make_unique_ref(3); makeInvalid(std::move(var2)); EXPECT_FALSE(std::less>()(var1, var2)); // NOLINT (intentional use-after-move) @@ -602,7 +602,7 @@ private: } TEST_F(UniqueRefTest, AllowsDerefOnRvalue) { - OnlyMoveable val = *make_unique_ref(5); + const OnlyMoveable val = *make_unique_ref(5); EXPECT_EQ(OnlyMoveable(5), val); } @@ -633,7 +633,7 @@ TEST_F(UniqueRefTest, givenUniqueRefWithDefaultDeleter_whenMoveConstructed_thenC bool wasDestructed = false; auto obj = make_unique_ref(&wasDestructed); { - unique_ref obj2 = std::move(obj); + const unique_ref obj2 = std::move(obj); EXPECT_FALSE(wasDestructed); } EXPECT_TRUE(wasDestructed); @@ -680,7 +680,7 @@ TEST_F(UniqueRefTest, givenUniqueRefWithCustomDefaultConstructibleDeleter_whenMo bool wasDestructed = false; unique_ref obj = nullcheck(std::unique_ptr(&wasDestructed)).value(); { - unique_ref obj2 = std::move(obj); + const unique_ref obj2 = std::move(obj); EXPECT_FALSE(wasDestructed); } EXPECT_TRUE(wasDestructed); @@ -730,7 +730,7 @@ TEST_F(UniqueRefTest, givenUniqueRefWithCustomDeleterInstance_whenMoveConstructe int value = 0; unique_ref obj = nullcheck(std::unique_ptr(&value, SetToDeleter(4))).value(); { - unique_ref obj2 = std::move(obj); + const unique_ref obj2 = std::move(obj); EXPECT_EQ(0, value); } EXPECT_EQ(4, value); @@ -758,7 +758,7 @@ TEST_F(UniqueRefTest, givenUniqueRefWithCustomDeleterInstance_whenDestructCalled TEST_F(UniqueRefTest, givenUniquePtrWithCustomDeleterInstance_whenMovedToUniquePtr_thenHasSameDeleterInstance) { int dummy = 0; - SetToDeleter deleter(4); + const SetToDeleter deleter(4); auto ptr = std::unique_ptr(&dummy, deleter); auto ref = nullcheck(std::move(ptr)).value(); EXPECT_EQ(4, ref.get_deleter().value_); @@ -766,7 +766,7 @@ TEST_F(UniqueRefTest, givenUniquePtrWithCustomDeleterInstance_whenMovedToUniqueP TEST_F(UniqueRefTest, givenUniqueRefWithCustomDeleterInstance_whenMoveConstructing_thenHasSameDeleterInstance) { int dummy = 0; - SetToDeleter deleter(4); + const SetToDeleter deleter(4); auto ref = nullcheck(std::unique_ptr(&dummy, deleter)).value(); unique_ref ref2 = std::move(ref); EXPECT_EQ(4, ref2.get_deleter().value_); @@ -774,7 +774,7 @@ TEST_F(UniqueRefTest, givenUniqueRefWithCustomDeleterInstance_whenMoveConstructi TEST_F(UniqueRefTest, givenUniqueRefWithCustomDeleterInstance_whenMoveAssigning_thenHasSameDeleterInstance) { int dummy = 0; - SetToDeleter deleter(4); + const SetToDeleter deleter(4); auto ref = nullcheck(std::unique_ptr(&dummy, deleter)).value(); auto ref2 = nullcheck(std::unique_ptr(&dummy, SetToDeleter(0))).value(); ref2 = std::move(ref); @@ -783,7 +783,7 @@ TEST_F(UniqueRefTest, givenUniqueRefWithCustomDeleterInstance_whenMoveAssigning_ TEST_F(UniqueRefTest, AllowsMoveConstructingToUniqueRefOfConst) { unique_ref a = make_unique_ref(3); - unique_ref b = std::move(a); + const unique_ref b = std::move(a); } TEST_F(UniqueRefTest, AllowsMoveAssigningToUniqueRefOfConst) { diff --git a/test/cpp-utils/process/SignalCatcherTest.cpp b/test/cpp-utils/process/SignalCatcherTest.cpp index f0d49fce..4a346da1 100644 --- a/test/cpp-utils/process/SignalCatcherTest.cpp +++ b/test/cpp-utils/process/SignalCatcherTest.cpp @@ -6,7 +6,7 @@ using cpputils::SignalCatcher; namespace { void raise_signal(int signal) { - int error = ::raise(signal); + const int error = ::raise(signal); if (error != 0) { throw std::runtime_error("Error raising signal"); } @@ -28,7 +28,7 @@ TEST(SignalCatcherTest, givenNoSignalCatcher_whenRaisingSigterm_thenDies) { } TEST(SignalCatcherTest, givenSigIntCatcher_whenRaisingSigInt_thenCatches) { - SignalCatcher catcher({SIGINT}); + const SignalCatcher catcher({SIGINT}); EXPECT_FALSE(catcher.signal_occurred()); raise_signal(SIGINT); @@ -40,7 +40,7 @@ TEST(SignalCatcherTest, givenSigIntCatcher_whenRaisingSigInt_thenCatches) { } TEST(SignalCatcherTest, givenSigTermCatcher_whenRaisingSigTerm_thenCatches) { - SignalCatcher catcher({SIGTERM}); + const SignalCatcher catcher({SIGTERM}); EXPECT_FALSE(catcher.signal_occurred()); raise_signal(SIGTERM); @@ -52,7 +52,7 @@ TEST(SignalCatcherTest, givenSigTermCatcher_whenRaisingSigTerm_thenCatches) { } TEST(SignalCatcherTest, givenSigIntAndSigTermCatcher_whenRaisingSigInt_thenCatches) { - SignalCatcher catcher({SIGINT, SIGTERM}); + const SignalCatcher catcher({SIGINT, SIGTERM}); EXPECT_FALSE(catcher.signal_occurred()); raise_signal(SIGINT); @@ -64,7 +64,7 @@ TEST(SignalCatcherTest, givenSigIntAndSigTermCatcher_whenRaisingSigInt_thenCatch } TEST(SignalCatcherTest, givenSigIntAndSigTermCatcher_whenRaisingSigTerm_thenCatches) { - SignalCatcher catcher({SIGINT, SIGTERM}); + const SignalCatcher catcher({SIGINT, SIGTERM}); EXPECT_FALSE(catcher.signal_occurred()); raise_signal(SIGTERM); @@ -76,7 +76,7 @@ TEST(SignalCatcherTest, givenSigIntAndSigTermCatcher_whenRaisingSigTerm_thenCatc } TEST(SignalCatcherTest, givenSigIntAndSigTermCatcher_whenRaisingSigIntAndSigTerm_thenCatches) { - SignalCatcher catcher({SIGINT, SIGTERM}); + const SignalCatcher catcher({SIGINT, SIGTERM}); EXPECT_FALSE(catcher.signal_occurred()); raise_signal(SIGTERM); @@ -87,8 +87,8 @@ TEST(SignalCatcherTest, givenSigIntAndSigTermCatcher_whenRaisingSigIntAndSigTerm } TEST(SignalCatcherTest, givenSigIntCatcherAndSigTermCatcher_whenRaisingSignalsInOrder_thenCorrectCatcherCatches) { - SignalCatcher sigintCatcher({SIGINT}); - SignalCatcher sigtermCatcher({SIGTERM}); + const SignalCatcher sigintCatcher({SIGINT}); + const SignalCatcher sigtermCatcher({SIGTERM}); EXPECT_FALSE(sigintCatcher.signal_occurred()); raise_signal(SIGINT); @@ -100,8 +100,8 @@ TEST(SignalCatcherTest, givenSigIntCatcherAndSigTermCatcher_whenRaisingSignalsIn } TEST(SignalCatcherTest, givenSigIntCatcherAndSigTermCatcher_whenRaisingSignalsInReverseOrder_thenCorrectCatcherCatches) { - SignalCatcher sigintCatcher({SIGINT}); - SignalCatcher sigtermCatcher({SIGTERM}); + const SignalCatcher sigintCatcher({SIGINT}); + const SignalCatcher sigtermCatcher({SIGTERM}); EXPECT_FALSE(sigtermCatcher.signal_occurred()); raise_signal(SIGTERM); @@ -113,16 +113,16 @@ TEST(SignalCatcherTest, givenSigIntCatcherAndSigTermCatcher_whenRaisingSignalsIn } TEST(SignalCatcherTest, givenNestedSigIntCatchers_whenRaisingSignals_thenCorrectCatcherCatches) { - SignalCatcher outerCatcher({SIGINT}); + const SignalCatcher outerCatcher({SIGINT}); { - SignalCatcher middleCatcher({SIGINT}); + const SignalCatcher middleCatcher({SIGINT}); EXPECT_FALSE(middleCatcher.signal_occurred()); raise_signal(SIGINT); EXPECT_TRUE(middleCatcher.signal_occurred()); { - SignalCatcher innerCatcher({SIGINT}); + const SignalCatcher innerCatcher({SIGINT}); EXPECT_FALSE(innerCatcher.signal_occurred()); raise_signal(SIGINT); @@ -137,7 +137,7 @@ TEST(SignalCatcherTest, givenNestedSigIntCatchers_whenRaisingSignals_thenCorrect TEST(SignalCatcherTest, givenExpiredSigIntCatcher_whenRaisingSigInt_thenDies) { { - SignalCatcher catcher({SIGINT}); + const SignalCatcher catcher({SIGINT}); } EXPECT_DEATH( @@ -148,7 +148,7 @@ TEST(SignalCatcherTest, givenExpiredSigIntCatcher_whenRaisingSigInt_thenDies) { TEST(SignalCatcherTest, givenExpiredSigTermCatcher_whenRaisingSigTerm_thenDies) { { - SignalCatcher catcher({SIGTERM}); + const SignalCatcher catcher({SIGTERM}); } EXPECT_DEATH( @@ -159,8 +159,8 @@ TEST(SignalCatcherTest, givenExpiredSigTermCatcher_whenRaisingSigTerm_thenDies) TEST(SignalCatcherTest, givenExpiredSigIntCatcherAndSigTermCatcher_whenRaisingSigTerm_thenDies) { { - SignalCatcher sigIntCatcher({SIGTERM}); - SignalCatcher sigTermCatcer({SIGTERM}); + const SignalCatcher sigIntCatcher({SIGTERM}); + const SignalCatcher sigTermCatcer({SIGTERM}); } EXPECT_DEATH( @@ -170,9 +170,9 @@ TEST(SignalCatcherTest, givenExpiredSigIntCatcherAndSigTermCatcher_whenRaisingSi } TEST(SignalCatcherTest, givenSigTermCatcherAndExpiredSigIntCatcher_whenRaisingSigTerm_thenCatches) { - SignalCatcher sigTermCatcher({SIGTERM}); + const SignalCatcher sigTermCatcher({SIGTERM}); { - SignalCatcher sigIntCatcher({SIGINT}); + const SignalCatcher sigIntCatcher({SIGINT}); } EXPECT_FALSE(sigTermCatcher.signal_occurred()); @@ -181,9 +181,9 @@ TEST(SignalCatcherTest, givenSigTermCatcherAndExpiredSigIntCatcher_whenRaisingSi } TEST(SignalCatcherTest, givenSigTermCatcherAndExpiredSigIntCatcher_whenRaisingSigInt_thenDies) { - SignalCatcher sigTermCacher({SIGTERM}); + const SignalCatcher sigTermCacher({SIGTERM}); { - SignalCatcher sigIntCatcher({SIGINT}); + const SignalCatcher sigIntCatcher({SIGINT}); } EXPECT_DEATH( diff --git a/test/cpp-utils/process/SignalHandlerTest.cpp b/test/cpp-utils/process/SignalHandlerTest.cpp index 194b2550..4e66b725 100644 --- a/test/cpp-utils/process/SignalHandlerTest.cpp +++ b/test/cpp-utils/process/SignalHandlerTest.cpp @@ -11,7 +11,7 @@ void trigger(int signal) { } void raise_signal(int signal) { - int error = ::raise(signal); + const int error = ::raise(signal); if (error != 0) { throw std::runtime_error("Error raising signal"); } @@ -34,14 +34,14 @@ TEST(SignalHandlerTest, givenNoSignalHandler_whenRaisingSigterm_thenDies) { TEST(SignalHandlerTest, givenSigIntHandler_whenRaisingSigInt_thenCatches) { triggered = 0; - SignalHandlerRAII<&trigger> handler(SIGINT); + const SignalHandlerRAII<&trigger> handler(SIGINT); raise_signal(SIGINT); EXPECT_EQ(SIGINT, triggered); } TEST(SignalHandlerTest, givenSigIntHandler_whenRaisingSigTerm_thenDies) { - SignalHandlerRAII<&trigger> handler(SIGINT); + const SignalHandlerRAII<&trigger> handler(SIGINT); EXPECT_DEATH( raise_signal(SIGTERM), @@ -52,14 +52,14 @@ TEST(SignalHandlerTest, givenSigIntHandler_whenRaisingSigTerm_thenDies) { TEST(SignalHandlerTest, givenSigTermHandler_whenRaisingSigTerm_thenCatches) { triggered = 0; - SignalHandlerRAII<&trigger> handler(SIGTERM); + const SignalHandlerRAII<&trigger> handler(SIGTERM); raise_signal(SIGTERM); EXPECT_EQ(SIGTERM, triggered); } TEST(SignalHandlerTest, givenSigTermHandler_whenRaisingSigInt_thenDies) { - SignalHandlerRAII<&trigger> handler(SIGTERM); + const SignalHandlerRAII<&trigger> handler(SIGTERM); EXPECT_DEATH( raise_signal(SIGINT), @@ -70,8 +70,8 @@ TEST(SignalHandlerTest, givenSigTermHandler_whenRaisingSigInt_thenDies) { TEST(SignalHandlerTest, givenSigIntAndSigTermHandlers_whenRaising_thenCatchesCorrectSignal) { triggered = 0; - SignalHandlerRAII<&trigger> handler1(SIGINT); - SignalHandlerRAII<&trigger> handler2(SIGTERM); + const SignalHandlerRAII<&trigger> handler1(SIGINT); + const SignalHandlerRAII<&trigger> handler2(SIGTERM); raise_signal(SIGINT); EXPECT_EQ(SIGINT, triggered); @@ -99,10 +99,10 @@ TEST(SignalHandlerTest, givenMultipleSigIntHandlers_whenRaising_thenCatchesCorre triggered_count_2 = 0; { - SignalHandlerRAII<&trigger1> handler1(SIGINT); + const SignalHandlerRAII<&trigger1> handler1(SIGINT); { - SignalHandlerRAII<&trigger2> handler2(SIGINT); + const SignalHandlerRAII<&trigger2> handler2(SIGINT); raise_signal(SIGINT); EXPECT_EQ(0, triggered_count_1); diff --git a/test/cpp-utils/process/exit_status.cpp b/test/cpp-utils/process/exit_status.cpp index b38eb9bd..7f517473 100644 --- a/test/cpp-utils/process/exit_status.cpp +++ b/test/cpp-utils/process/exit_status.cpp @@ -16,6 +16,6 @@ int main(int argc, char *argv[]) std::cout << argv[i] << "\n"; } - int exit_status = static_cast(std::strtol(argv[1], nullptr, 10)); + const int exit_status = static_cast(std::strtol(argv[1], nullptr, 10)); return exit_status; } diff --git a/test/cpp-utils/system/EnvTest.cpp b/test/cpp-utils/system/EnvTest.cpp index 802071cc..9f5170b1 100644 --- a/test/cpp-utils/system/EnvTest.cpp +++ b/test/cpp-utils/system/EnvTest.cpp @@ -4,14 +4,21 @@ using std::string; +namespace { + string read_env(const char* key) { + const char* value = std::getenv(key); + return value != nullptr ? string(value) : string(); + } +} + TEST(EnvTest, SetAndGetEnv_ValueIsCorrect) { cpputils::setenv("my_key", "my_value"); - EXPECT_EQ(string("my_value"), string(std::getenv("my_key"))); + EXPECT_EQ(string("my_value"), read_env("my_key")); } TEST(EnvTest, SetAndGetEnvWithSpacedValue_ValueIsCorrect) { cpputils::setenv("my_key", "my value with spaces"); - EXPECT_EQ(string("my value with spaces"), string(std::getenv("my_key"))); + EXPECT_EQ(string("my value with spaces"), read_env("my_key")); } TEST(EnvTest, UnsetAndGetEnv_ValueIsEmpty) { diff --git a/test/cpp-utils/system/FiletimeTest.cpp b/test/cpp-utils/system/FiletimeTest.cpp index 09c1b9a7..2dc07a30 100644 --- a/test/cpp-utils/system/FiletimeTest.cpp +++ b/test/cpp-utils/system/FiletimeTest.cpp @@ -7,9 +7,9 @@ using cpputils::set_filetime; using cpputils::get_filetime; TEST(FiletimeTest, SetAndGetTime_ReturnsCorrectTime) { - TempFile file; - struct timespec accessTime { 1535965242, 12345000 }; - struct timespec modificationTime { 1435965242, 98765000 }; + const TempFile file; + const struct timespec accessTime { 1535965242, 12345000 }; + const struct timespec modificationTime { 1435965242, 98765000 }; int retval = set_filetime(file.path().string().c_str(), accessTime, modificationTime); EXPECT_EQ(0, retval); diff --git a/test/cpp-utils/system/GetTotalMemoryTest.cpp b/test/cpp-utils/system/GetTotalMemoryTest.cpp index 81c57f48..4a4d0cbe 100644 --- a/test/cpp-utils/system/GetTotalMemoryTest.cpp +++ b/test/cpp-utils/system/GetTotalMemoryTest.cpp @@ -8,6 +8,6 @@ TEST(GetTotalMemoryTest, DoesntCrash) { } TEST(GetTotalMemoryTest, IsNotZero) { - uint64_t mem = get_total_memory(); + const uint64_t mem = get_total_memory(); EXPECT_LT(UINT64_C(0), mem); } diff --git a/test/cpp-utils/system/HomedirTest.cpp b/test/cpp-utils/system/HomedirTest.cpp index a19ec867..e00813e0 100644 --- a/test/cpp-utils/system/HomedirTest.cpp +++ b/test/cpp-utils/system/HomedirTest.cpp @@ -20,20 +20,22 @@ TEST(HomedirTest, AppDataDirIsValid) { } TEST(HomedirTest, FakeHomeDirectorySetsHomedirCorrectly) { - TempDir fakeHomeDir, fakeAppDataDir; - FakeHomeDirectoryRAII a(fakeHomeDir.path(), fakeAppDataDir.path()); + const TempDir fakeHomeDir; + const TempDir fakeAppDataDir; + const FakeHomeDirectoryRAII a(fakeHomeDir.path(), fakeAppDataDir.path()); EXPECT_EQ(fakeHomeDir.path(), HomeDirectory::get()); EXPECT_EQ(fakeAppDataDir.path(), HomeDirectory::getXDGDataDir()); } TEST(HomedirTest, FakeHomeDirectoryResetsHomedirCorrectly) { - bf::path actualHomeDir = HomeDirectory::get(); - bf::path actualAppDataDir = HomeDirectory::getXDGDataDir(); + const bf::path actualHomeDir = HomeDirectory::get(); + const bf::path actualAppDataDir = HomeDirectory::getXDGDataDir(); { - TempDir fakeHomeDir, fakeAppDataDir; - FakeHomeDirectoryRAII a(fakeHomeDir.path(), fakeAppDataDir.path()); + const TempDir fakeHomeDir; + const TempDir fakeAppDataDir; + const FakeHomeDirectoryRAII a(fakeHomeDir.path(), fakeAppDataDir.path()); EXPECT_NE(actualHomeDir, HomeDirectory::get()); EXPECT_NE(actualAppDataDir, HomeDirectory::getXDGDataDir()); @@ -43,21 +45,21 @@ TEST(HomedirTest, FakeHomeDirectoryResetsHomedirCorrectly) { } TEST(HomedirTest, FakeTempHomeDirectorySetsHomedirCorrectly) { - bf::path actualHomeDir = HomeDirectory::get(); - bf::path actualAppDataDir = HomeDirectory::getXDGDataDir(); + const bf::path actualHomeDir = HomeDirectory::get(); + const bf::path actualAppDataDir = HomeDirectory::getXDGDataDir(); - FakeTempHomeDirectoryRAII a; + const FakeTempHomeDirectoryRAII a; EXPECT_NE(actualHomeDir, HomeDirectory::get()); EXPECT_NE(actualAppDataDir, HomeDirectory::getXDGDataDir()); } TEST(HomedirTest, FakeTempHomeDirectoryResetsHomedirCorrectly) { - bf::path actualHomeDir = HomeDirectory::get(); - bf::path actualAppDataDir = HomeDirectory::getXDGDataDir(); + const bf::path actualHomeDir = HomeDirectory::get(); + const bf::path actualAppDataDir = HomeDirectory::getXDGDataDir(); { - FakeTempHomeDirectoryRAII a; + const FakeTempHomeDirectoryRAII a; EXPECT_NE(actualHomeDir, HomeDirectory::get()); EXPECT_NE(actualAppDataDir, HomeDirectory::getXDGDataDir()); @@ -67,7 +69,7 @@ TEST(HomedirTest, FakeTempHomeDirectoryResetsHomedirCorrectly) { } TEST(HomedirTest, FakeTempHomeDirectoryUsesDifferentDirsForHomedirAndAppdataDir) { - FakeTempHomeDirectoryRAII a; + const FakeTempHomeDirectoryRAII a; EXPECT_NE(HomeDirectory::get(), HomeDirectory::getXDGDataDir()); } diff --git a/test/cpp-utils/system/TimeTest.cpp b/test/cpp-utils/system/TimeTest.cpp index 24b8deb4..e0dab171 100644 --- a/test/cpp-utils/system/TimeTest.cpp +++ b/test/cpp-utils/system/TimeTest.cpp @@ -18,21 +18,21 @@ TEST(TimeTest, DoesntCrash) { } TEST(TimeTest, IsLaterThanYear2010) { - struct timespec current_time = now(); + const struct timespec current_time = now(); constexpr time_t year_2010_timestamp = 1262304000; EXPECT_LT(year_2010_timestamp, current_time.tv_sec); } TEST(TimeTest, IsNondecreasing) { - uint64_t time1 = _to_nanos(now()); - uint64_t time2 = _to_nanos(now()); + const uint64_t time1 = _to_nanos(now()); + const uint64_t time2 = _to_nanos(now()); EXPECT_LE(time1, time2); } TEST(TimeTest, IsIncreasedAfterPause) { - uint64_t time1 = _to_nanos(now()); + const uint64_t time1 = _to_nanos(now()); std::this_thread::sleep_for(std::chrono::milliseconds(10)); - uint64_t time2 = _to_nanos(now()); + const uint64_t time2 = _to_nanos(now()); EXPECT_LT(time1, time2); } diff --git a/test/cpp-utils/tempfile/TempDirTest.cpp b/test/cpp-utils/tempfile/TempDirTest.cpp index baf68350..f965ed9c 100644 --- a/test/cpp-utils/tempfile/TempDirTest.cpp +++ b/test/cpp-utils/tempfile/TempDirTest.cpp @@ -14,7 +14,7 @@ namespace bf = boost::filesystem; class TempDirTest: public Test { public: void EXPECT_ENTRY_COUNT(int expected, const bf::path &path) { - int actual = CountEntries(path); + const int actual = CountEntries(path); EXPECT_EQ(expected, actual); } @@ -27,23 +27,23 @@ public: } void CreateFile(const bf::path &path) { - ofstream file(path.string().c_str()); + const ofstream file(path.string().c_str()); } }; TEST_F(TempDirTest, DirIsCreated) { - TempDir dir; + const TempDir dir; EXPECT_TRUE(bf::exists(dir.path())); EXPECT_TRUE(bf::is_directory(dir.path())); } TEST_F(TempDirTest, DirIsCreatedEmpty) { - TempDir dir; + const TempDir dir; EXPECT_ENTRY_COUNT(0, dir.path()); } TEST_F(TempDirTest, DirIsWriteable) { - TempDir dir; + const TempDir dir; CreateFile(dir.path() / "myfile"); EXPECT_ENTRY_COUNT(1, dir.path()); } @@ -51,7 +51,7 @@ TEST_F(TempDirTest, DirIsWriteable) { TEST_F(TempDirTest, DirIsDeletedAfterUse) { bf::path dirpath; { - TempDir dir; + const TempDir dir; dirpath = dir.path(); } EXPECT_FALSE(bf::exists(dirpath)); diff --git a/test/cpp-utils/tempfile/TempFileTest.cpp b/test/cpp-utils/tempfile/TempFileTest.cpp index 40d38288..fa170c84 100644 --- a/test/cpp-utils/tempfile/TempFileTest.cpp +++ b/test/cpp-utils/tempfile/TempFileTest.cpp @@ -21,51 +21,51 @@ public: bf::path filepath_sample; void CreateFile(const bf::path &path) { - ofstream file(path.string().c_str()); + const ofstream file(path.string().c_str()); } }; TEST_F(TempFileTest, FileIsCreated) { - TempFile file; + const TempFile file; EXPECT_TRUE(bf::exists(file.path())); EXPECT_TRUE(bf::is_regular_file(file.path())); } TEST_F(TempFileTest, FileIsReadable) { - TempFile file; - ifstream opened(file.path().string().c_str()); + const TempFile file; + const ifstream opened(file.path().string().c_str()); EXPECT_TRUE(opened.good()); } TEST_F(TempFileTest, FileIsCreatedEmpty) { - TempFile file; + const TempFile file; ifstream opened(file.path().string().c_str()); opened.get(); EXPECT_TRUE(opened.eof()); } TEST_F(TempFileTest, FileIsWriteable) { - TempFile file; - ofstream opened(file.path().string().c_str()); + const TempFile file; + const ofstream opened(file.path().string().c_str()); EXPECT_TRUE(opened.good()); } TEST_F(TempFileTest, FileIsDeletedAfterUse) { bf::path filepath; { - TempFile file; + const TempFile file; filepath = file.path(); } EXPECT_FALSE(bf::exists(filepath)); } TEST_F(TempFileTest, DontCreateFileSpecified_FileIsNotCreated) { - TempFile file(false); + const TempFile file(false); EXPECT_FALSE(bf::exists(file.path())); } TEST_F(TempFileTest, DontCreateFileSpecified_FileIsCreatable) { - TempFile file(false); + const TempFile file(false); CreateFile(file.path()); EXPECT_TRUE(bf::exists(file.path())); } @@ -73,7 +73,7 @@ TEST_F(TempFileTest, DontCreateFileSpecified_FileIsCreatable) { TEST_F(TempFileTest, DontCreateFileSpecified_FileIsDeletedAfterUse) { bf::path filepath; { - TempFile file(false); + const TempFile file(false); CreateFile(file.path()); filepath = file.path(); } @@ -81,36 +81,36 @@ TEST_F(TempFileTest, DontCreateFileSpecified_FileIsDeletedAfterUse) { } TEST_F(TempFileTest, PathGiven_FileIsCreatedAtGivenPath) { - TempFile file(filepath_sample); + const TempFile file(filepath_sample); EXPECT_EQ(filepath_sample, file.path()); } TEST_F(TempFileTest, PathGiven_FileIsCreatedAndAccessible) { - TempFile file(filepath_sample); + const TempFile file(filepath_sample); EXPECT_TRUE(bf::exists(filepath_sample)); } TEST_F(TempFileTest, PathGiven_FileIsDeletedAfterUse) { { - TempFile file(filepath_sample); + const TempFile file(filepath_sample); } EXPECT_FALSE(bf::exists(filepath_sample)); } TEST_F(TempFileTest, PathGiven_DontCreateFileSpecified_FileIsNotCreated) { - TempFile file(filepath_sample, false); + const TempFile file(filepath_sample, false); EXPECT_FALSE(bf::exists(filepath_sample)); } TEST_F(TempFileTest, PathGiven_DontCreateFileSpecified_FileIsCreatable) { - TempFile file(filepath_sample, false); + const TempFile file(filepath_sample, false); CreateFile(filepath_sample); EXPECT_TRUE(bf::exists(filepath_sample)); } TEST_F(TempFileTest, PathGiven_DontCreateFileSpecified_FileIsDeletedAfterUse) { { - TempFile file(filepath_sample, false); + const TempFile file(filepath_sample, false); CreateFile(filepath_sample); } EXPECT_FALSE(bf::exists(filepath_sample)); diff --git a/test/cpp-utils/thread/LeftRightTest.cpp b/test/cpp-utils/thread/LeftRightTest.cpp index 851d2d47..ebe4cd00 100644 --- a/test/cpp-utils/thread/LeftRightTest.cpp +++ b/test/cpp-utils/thread/LeftRightTest.cpp @@ -148,7 +148,7 @@ class MyException : std::exception {}; } TEST(LeftRightTest, whenReadThrowsException_thenThrowsThrough) { - LeftRight obj; + const LeftRight obj; EXPECT_THROW( obj.read([](auto&) {throw MyException();}), diff --git a/test/cpp-utils/thread/debugging_test.cpp b/test/cpp-utils/thread/debugging_test.cpp index caf5f458..284bbcd7 100644 --- a/test/cpp-utils/thread/debugging_test.cpp +++ b/test/cpp-utils/thread/debugging_test.cpp @@ -13,14 +13,14 @@ TEST(ThreadDebuggingTest_ThreadName, givenMainThread_whenSettingAndGetting_thenD TEST(ThreadDebuggingTest_ThreadName, givenMainThread_whenGettingFromInside_thenIsCorrect) { set_thread_name("my_thread_name"); - string name = get_thread_name(); + const string name = get_thread_name(); EXPECT_EQ("my_thread_name", name); } TEST(ThreadDebuggingTest_ThreadName, givenChildThread_whenGettingFromInside_thenIsCorrect) { std::thread child([] { set_thread_name("my_thread_name"); - string name = get_thread_name(); + const string name = get_thread_name(); EXPECT_EQ("my_thread_name", name); }); child.join(); @@ -57,7 +57,7 @@ TEST(ThreadDebuggingTest_ThreadName, givenChildThread_whenGettingFromOutside_the nameIsSet.wait(); set_thread_name("outer_thread_name"); // just to make sure the next line doesn't read the outer thread name - string name = get_thread_name(&child); + const string name = get_thread_name(&child); EXPECT_EQ("my_thread_name", name); nameIsChecked.release(); diff --git a/test/cpp-utils/value_type/ValueTypeTest.cpp b/test/cpp-utils/value_type/ValueTypeTest.cpp index cb984d38..1fa957a9 100644 --- a/test/cpp-utils/value_type/ValueTypeTest.cpp +++ b/test/cpp-utils/value_type/ValueTypeTest.cpp @@ -92,9 +92,9 @@ TYPED_TEST_SUITE(IdValueTypeTest, IdValueTypeTest_types); TYPED_TEST(IdValueTypeTest, Equality) { - TypeParam obj1(4); - TypeParam obj2(4); - TypeParam obj3(5); + const TypeParam obj1(4); + const TypeParam obj2(4); + const TypeParam obj3(5); EXPECT_TRUE(obj1 == obj2); EXPECT_TRUE(obj2 == obj1);; @@ -108,25 +108,25 @@ TYPED_TEST(IdValueTypeTest, Equality) { } TYPED_TEST(IdValueTypeTest, Constructor) { - TypeParam obj(4); + const TypeParam obj(4); EXPECT_TRUE(obj == TypeParam(4)); } TYPED_TEST(IdValueTypeTest, CopyConstructor) { - TypeParam obj(2); - TypeParam obj2(obj); + const TypeParam obj(2); + const TypeParam obj2(obj); EXPECT_TRUE(obj2 == TypeParam(2)); EXPECT_TRUE(obj == obj2); } TYPED_TEST(IdValueTypeTest, MoveConstructor) { TypeParam obj(2); - TypeParam obj2(std::move(obj)); + const TypeParam obj2(std::move(obj)); EXPECT_TRUE(obj2 == TypeParam(2)); } TYPED_TEST(IdValueTypeTest, CopyAssignment) { - TypeParam obj(3); + const TypeParam obj(3); TypeParam obj2(2); obj2 = obj; EXPECT_TRUE(obj2 == TypeParam(3)); @@ -134,7 +134,7 @@ TYPED_TEST(IdValueTypeTest, CopyAssignment) { } TYPED_TEST(IdValueTypeTest, CopyAssignment_Return) { - TypeParam obj(3); + const TypeParam obj(3); TypeParam obj2(2); EXPECT_TRUE((obj2 = obj) == TypeParam(3)); } @@ -153,8 +153,8 @@ TYPED_TEST(IdValueTypeTest, MoveAssignment_Return) { } TYPED_TEST(IdValueTypeTest, Hash) { - TypeParam obj(3); - TypeParam obj2(3); + const TypeParam obj(3); + const TypeParam obj2(3); EXPECT_EQ(std::hash()(obj), std::hash()(obj2)); } @@ -210,9 +210,9 @@ using OrderedIdValueTypeTest_types = testing::Types a); EXPECT_FALSE(a > b); EXPECT_FALSE(a > c); @@ -240,9 +240,9 @@ TYPED_TEST(OrderedIdValueTypeTest, GreaterThan) { } TYPED_TEST(OrderedIdValueTypeTest, LessOrEqualThan) { - TypeParam a(3); - TypeParam b(3); - TypeParam c(4); + const TypeParam a(3); + const TypeParam b(3); + const TypeParam c(4); EXPECT_TRUE(a <= a); EXPECT_TRUE(a <= b); EXPECT_TRUE(a <= c); @@ -255,9 +255,9 @@ TYPED_TEST(OrderedIdValueTypeTest, LessOrEqualThan) { } TYPED_TEST(OrderedIdValueTypeTest, GreaterOrEqualThan) { - TypeParam a(3); - TypeParam b(3); - TypeParam c(4); + const TypeParam a(3); + const TypeParam b(3); + const TypeParam c(4); EXPECT_TRUE(a >= a); EXPECT_TRUE(a >= b); EXPECT_FALSE(a >= c); @@ -441,7 +441,7 @@ TYPED_TEST_SUITE(FlagsValueTypeTest, FlagsValueType_types); TYPED_TEST(FlagsValueTypeTest, Invert) { TypeParam a(3); - TypeParam b(~3); + const TypeParam b(~3); EXPECT_EQ(b, ~a); a = ~a; @@ -449,9 +449,9 @@ TYPED_TEST(FlagsValueTypeTest, Invert) { } TYPED_TEST(FlagsValueTypeTest, And) { - TypeParam a(3); + const TypeParam a(3); TypeParam b(5); - TypeParam c(3 & 5); + const TypeParam c(3 & 5); EXPECT_EQ(c, a & b); EXPECT_EQ(c, b &= a); @@ -459,9 +459,9 @@ TYPED_TEST(FlagsValueTypeTest, And) { } TYPED_TEST(FlagsValueTypeTest, Or) { - TypeParam a(3); + const TypeParam a(3); TypeParam b(5); - TypeParam c(3 | 5); + const TypeParam c(3 | 5); EXPECT_EQ(c, a | b); EXPECT_EQ(c, b |= a); @@ -469,9 +469,9 @@ TYPED_TEST(FlagsValueTypeTest, Or) { } TYPED_TEST(FlagsValueTypeTest, Xor) { - TypeParam a(3); + const TypeParam a(3); TypeParam b(5); - TypeParam c(3 ^ 5); + const TypeParam c(3 ^ 5); EXPECT_EQ(c, a ^ b); EXPECT_EQ(c, b ^= a); diff --git a/test/cryfs-cli/CliTest_IntegrityCheck.cpp b/test/cryfs-cli/CliTest_IntegrityCheck.cpp index 4ac5c30c..c72d8feb 100644 --- a/test/cryfs-cli/CliTest_IntegrityCheck.cpp +++ b/test/cryfs-cli/CliTest_IntegrityCheck.cpp @@ -84,7 +84,7 @@ public: }; TEST_F(CliTest_IntegrityCheck, givenIncorrectFilesystemId_thenFails) { - vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; + const vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS can handle that EXPECT_RUN_SUCCESS(args, mountdir); modifyFilesystemId(); @@ -96,7 +96,7 @@ TEST_F(CliTest_IntegrityCheck, givenIncorrectFilesystemId_thenFails) { } TEST_F(CliTest_IntegrityCheck, givenIncorrectFilesystemKey_thenFails) { - vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; + const vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS can handle that EXPECT_RUN_SUCCESS(args, mountdir); modifyFilesystemKey(); @@ -109,7 +109,7 @@ TEST_F(CliTest_IntegrityCheck, givenIncorrectFilesystemKey_thenFails) { // TODO Also enable this TEST_F(CliTest_IntegrityCheck, givenFilesystemWithRolledBackBasedir_whenMounting_thenFails) { - vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; + const vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS/EXPECT_RUN_ERROR can handle that // create a filesystem with one file @@ -118,7 +118,7 @@ TEST_F(CliTest_IntegrityCheck, givenFilesystemWithRolledBackBasedir_whenMounting }); // backup the base directory - TempDir backup; + const TempDir backup; recursive_copy(basedir, backup.path() / "basedir"); // modify the file system contents @@ -140,7 +140,7 @@ TEST_F(CliTest_IntegrityCheck, givenFilesystemWithRolledBackBasedir_whenMounting } TEST_F(CliTest_IntegrityCheck, whenRollingBackBasedirWhileMounted_thenUnmounts) { - vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; + const vector args{basedir.string().c_str(), mountdir.string().c_str(), "--cipher", "aes-256-gcm", "-f"}; //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS/EXPECT_RUN_ERROR can handle that // create a filesystem with one file @@ -149,7 +149,7 @@ TEST_F(CliTest_IntegrityCheck, whenRollingBackBasedirWhileMounted_thenUnmounts) }); // backup the base directory - TempDir backup; + const TempDir backup; recursive_copy(basedir, backup.path() / "basedir"); EXPECT_RUN_ERROR(args, "Integrity violation detected. Unmounting.", ErrorCode::IntegrityViolation, [&] { diff --git a/test/cryfs-cli/CliTest_Setup.cpp b/test/cryfs-cli/CliTest_Setup.cpp index a9457180..f5766dfa 100644 --- a/test/cryfs-cli/CliTest_Setup.cpp +++ b/test/cryfs-cli/CliTest_Setup.cpp @@ -15,7 +15,7 @@ TEST_F(CliTest_Setup, NoSpecialOptions) { } TEST_F(CliTest_Setup, NotexistingLogfileGiven) { - TempFile notexisting_logfile(false); + const TempFile notexisting_logfile(false); //Specify --cipher parameter to make it non-interactive //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS can handle that EXPECT_RUN_SUCCESS({basedir.string().c_str(), mountdir.string().c_str(), "-f", "--cipher", "aes-256-gcm", "--logfile", notexisting_logfile.path().string().c_str()}, mountdir); @@ -36,14 +36,14 @@ TEST_F(CliTest_Setup, ConfigfileGiven) { } TEST_F(CliTest_Setup, AutocreateBasedir) { - TempFile notexisting_basedir(false); + const TempFile notexisting_basedir(false); //Specify --cipher parameter to make it non-interactive //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS can handle that EXPECT_RUN_SUCCESS({notexisting_basedir.path().string().c_str(), mountdir.string().c_str(), "-f", "--cipher", "aes-256-gcm", "--create-missing-basedir"}, mountdir); } TEST_F(CliTest_Setup, AutocreateBasedirFail) { - TempFile notexisting_basedir(false); + const TempFile notexisting_basedir(false); //Specify --cipher parameter to make it non-interactive //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS can handle that EXPECT_RUN_ERROR( @@ -54,14 +54,14 @@ TEST_F(CliTest_Setup, AutocreateBasedirFail) { } TEST_F(CliTest_Setup, AutocreateMountpoint) { - TempFile notexisting_mountpoint(false); + const TempFile notexisting_mountpoint(false); //Specify --cipher parameter to make it non-interactive //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS can handle that EXPECT_RUN_SUCCESS({basedir.string().c_str(), notexisting_mountpoint.path().string().c_str(), "-f", "--cipher", "aes-256-gcm", "--create-missing-mountpoint"}, notexisting_mountpoint.path()); } TEST_F(CliTest_Setup, AutocreateMountdirFail) { - TempFile notexisting_mountdir(false); + const TempFile notexisting_mountdir(false); //Specify --cipher parameter to make it non-interactive //TODO Remove "-f" parameter, once EXPECT_RUN_SUCCESS can handle that EXPECT_RUN_ERROR( diff --git a/test/cryfs-cli/CliTest_WrongEnvironment.cpp b/test/cryfs-cli/CliTest_WrongEnvironment.cpp index 7fe5fd09..42de4f60 100644 --- a/test/cryfs-cli/CliTest_WrongEnvironment.cpp +++ b/test/cryfs-cli/CliTest_WrongEnvironment.cpp @@ -93,7 +93,7 @@ TEST_P(CliTest_WrongEnvironment, MountDirIsBaseDir) { bf::path make_relative(const bf::path &path) { bf::path result; - bf::path cwd = bf::current_path(); + const bf::path cwd = bf::current_path(); for(auto iter = ++cwd.begin(); iter!=cwd.end(); ++iter) { result /= ".."; } @@ -144,7 +144,7 @@ TEST_P(CliTest_WrongEnvironment, BaseDir_DoesntExist_Create) { } TEST_P(CliTest_WrongEnvironment, BaseDir_IsNotDirectory) { - TempFile basedirfile; + const TempFile basedirfile; basedir = basedirfile.path(); Test_Run_Error("Error 16: base directory is not a directory", ErrorCode::InaccessibleBaseDir); } @@ -205,7 +205,7 @@ TEST_P(CliTest_WrongEnvironment, MountDir_DoesntExist_Create) { } TEST_P(CliTest_WrongEnvironment, MountDir_IsNotDirectory) { - TempFile mountdirfile; + const TempFile mountdirfile; mountdir = mountdirfile.path(); Test_Run_Error("Error 17: mount directory is not a directory", ErrorCode::InaccessibleMountDir); } diff --git a/test/cryfs-cli/EnvironmentTest.cpp b/test/cryfs-cli/EnvironmentTest.cpp index 017ce21e..7ae21b14 100644 --- a/test/cryfs-cli/EnvironmentTest.cpp +++ b/test/cryfs-cli/EnvironmentTest.cpp @@ -49,12 +49,12 @@ TEST_F(EnvironmentTest, Noninteractive_Unset) { } TEST_F(EnvironmentTest, Noninteractive_Set) { - WithEnv env("CRYFS_FRONTEND", "noninteractive"); + const WithEnv env("CRYFS_FRONTEND", "noninteractive"); EXPECT_TRUE(Environment::isNoninteractive()); } TEST_F(EnvironmentTest, Noninteractive_SetToOtherValue) { - WithEnv env("CRYFS_FRONTEND", "someotherfrontend"); + const WithEnv env("CRYFS_FRONTEND", "someotherfrontend"); EXPECT_FALSE(Environment::isNoninteractive()); } @@ -63,12 +63,12 @@ TEST_F(EnvironmentTest, NoUpdateCheck_Unset) { } TEST_F(EnvironmentTest, NoUpdateCheck_Set) { - WithEnv env("CRYFS_NO_UPDATE_CHECK", "true"); + const WithEnv env("CRYFS_NO_UPDATE_CHECK", "true"); EXPECT_TRUE(Environment::noUpdateCheck()); } TEST_F(EnvironmentTest, NoUpdateCheck_SetToOtherValue) { - WithEnv env("CRYFS_NO_UPDATE_CHECK", "someothervalue"); + const WithEnv env("CRYFS_NO_UPDATE_CHECK", "someothervalue"); // No matter what the value is, setting the environment variable says we don't do update checks. EXPECT_TRUE(Environment::noUpdateCheck()); } @@ -78,16 +78,16 @@ TEST_F(EnvironmentTest, LocalStateDir_NotSet) { } TEST_F(EnvironmentTest, LocalStateDir_Set) { - WithEnv env("CRYFS_LOCAL_STATE_DIR", some_local_state_dir); + const WithEnv env("CRYFS_LOCAL_STATE_DIR", some_local_state_dir); EXPECT_EQ(some_local_state_dir, Environment::localStateDir().string()); } TEST_F(EnvironmentTest, LocalStateDir_ConvertsRelativeToAbsolutePath_WithDot) { - WithEnv env("CRYFS_LOCAL_STATE_DIR", "./dir"); + const WithEnv env("CRYFS_LOCAL_STATE_DIR", "./dir"); EXPECT_EQ((bf::current_path() / "./dir").string(), Environment::localStateDir().string()); } TEST_F(EnvironmentTest, LocalStateDir_ConvertsRelativeToAbsolutePath_WithoutDot) { - WithEnv env("CRYFS_LOCAL_STATE_DIR", "dir"); + const WithEnv env("CRYFS_LOCAL_STATE_DIR", "dir"); EXPECT_EQ((bf::current_path() / "dir").string(), Environment::localStateDir().string()); } diff --git a/test/cryfs-cli/program_options/ParserTest.cpp b/test/cryfs-cli/program_options/ParserTest.cpp index 245b9148..46b10bd4 100644 --- a/test/cryfs-cli/program_options/ParserTest.cpp +++ b/test/cryfs-cli/program_options/ParserTest.cpp @@ -90,102 +90,102 @@ TEST_F(ProgramOptionsParserTest, ShowCiphers) { } TEST_F(ProgramOptionsParserTest, BaseDir_Absolute) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(basedir, options.baseDir()); } TEST_F(ProgramOptionsParserTest, Basedir_Relative) { - ProgramOptions options = parse({"./myExecutable", "baseDir", mountdir}); + const ProgramOptions options = parse({"./myExecutable", "baseDir", mountdir}); EXPECT_EQ(bf::current_path() / "baseDir", options.baseDir()); } TEST_F(ProgramOptionsParserTest, MountDir_Absolute) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(mountdir, options.mountDir()); } TEST_F(ProgramOptionsParserTest, MountDir_Relative) { - ProgramOptions options = parse({"./myExecutable", basedir, "mountDir"}); + const ProgramOptions options = parse({"./myExecutable", basedir, "mountDir"}); EXPECT_EQ(bf::current_path() / "mountDir", options.mountDir()); } TEST_F(ProgramOptionsParserTest, Foreground_False) { - ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); EXPECT_FALSE(options.foreground()); } TEST_F(ProgramOptionsParserTest, Foreground_True) { - ProgramOptions options = parse({"./myExecutable", "-f", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", "-f", basedir, "mountdir"}); EXPECT_TRUE(options.foreground()); } TEST_F(ProgramOptionsParserTest, AllowFilesystemUpgrade_False) { - ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); EXPECT_FALSE(options.allowFilesystemUpgrade()); } TEST_F(ProgramOptionsParserTest, AllowFilesystemUpgrade_True) { - ProgramOptions options = parse({"./myExecutable", "--allow-filesystem-upgrade", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", "--allow-filesystem-upgrade", basedir, "mountdir"}); EXPECT_TRUE(options.allowFilesystemUpgrade()); } TEST_F(ProgramOptionsParserTest, CreateMissingBasedir_False) { - ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); EXPECT_FALSE(options.createMissingBasedir()); } TEST_F(ProgramOptionsParserTest, CreateMissingBasedir_True) { - ProgramOptions options = parse({"./myExecutable", "--create-missing-basedir", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", "--create-missing-basedir", basedir, "mountdir"}); EXPECT_TRUE(options.createMissingBasedir()); } TEST_F(ProgramOptionsParserTest, CreateMissingMountpoint_False) { - ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", basedir, "mountdir"}); EXPECT_FALSE(options.createMissingMountpoint()); } TEST_F(ProgramOptionsParserTest, CreateMissingMountpoint_True) { - ProgramOptions options = parse({"./myExecutable", "--create-missing-mountpoint", basedir, "mountdir"}); + const ProgramOptions options = parse({"./myExecutable", "--create-missing-mountpoint", basedir, "mountdir"}); EXPECT_TRUE(options.createMissingMountpoint()); } TEST_F(ProgramOptionsParserTest, LogfileGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, "--logfile", logfile, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--logfile", logfile, mountdir}); EXPECT_EQ(logfile, options.logFile().value()); } TEST_F(ProgramOptionsParserTest, LogfileGiven_RelativePath) { - ProgramOptions options = parse({"./myExecutable", basedir, "--logfile", "mylogfile", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--logfile", "mylogfile", mountdir}); EXPECT_EQ(bf::current_path() / "mylogfile", options.logFile().value()); } TEST_F(ProgramOptionsParserTest, LogfileNotGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(none, options.logFile()); } TEST_F(ProgramOptionsParserTest, ConfigfileGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, "--config", configfile, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--config", configfile, mountdir}); EXPECT_EQ(configfile, options.configFile().value()); } TEST_F(ProgramOptionsParserTest, ConfigfileGiven_RelativePath) { - ProgramOptions options = parse({"./myExecutable", basedir, "--config", "myconfigfile", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--config", "myconfigfile", mountdir}); EXPECT_EQ(bf::current_path() / "myconfigfile", options.configFile().value()); } TEST_F(ProgramOptionsParserTest, ConfigfileNotGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(none, options.configFile()); } TEST_F(ProgramOptionsParserTest, CipherGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, "--cipher", "aes-256-gcm", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--cipher", "aes-256-gcm", mountdir}); EXPECT_EQ("aes-256-gcm", options.cipher().value()); } TEST_F(ProgramOptionsParserTest, CipherNotGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(none, options.cipher()); } @@ -200,92 +200,92 @@ TEST_F(ProgramOptionsParserTest, InvalidCipher) { } TEST_F(ProgramOptionsParserTest, UnmountAfterIdleMinutesGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, "--unmount-idle", "10", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--unmount-idle", "10", mountdir}); EXPECT_EQ(10, options.unmountAfterIdleMinutes().value()); } TEST_F(ProgramOptionsParserTest, UnmountAfterIdleMinutesGiven_Float) { - ProgramOptions options = parse({"./myExecutable", basedir, "--unmount-idle", "0.5", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--unmount-idle", "0.5", mountdir}); EXPECT_EQ(0.5, options.unmountAfterIdleMinutes().value()); } TEST_F(ProgramOptionsParserTest, UnmountAfterIdleMinutesNotGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(none, options.unmountAfterIdleMinutes()); } TEST_F(ProgramOptionsParserTest, BlocksizeGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, "--blocksize", "10240", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--blocksize", "10240", mountdir}); EXPECT_EQ(10240u, options.blocksizeBytes().value()); } TEST_F(ProgramOptionsParserTest, BlocksizeNotGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(none, options.blocksizeBytes()); } TEST_F(ProgramOptionsParserTest, MissingBlockIsIntegrityViolationGiven_True) { - ProgramOptions options = parse({"./myExecutable", basedir, "--missing-block-is-integrity-violation", "true", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--missing-block-is-integrity-violation", "true", mountdir}); EXPECT_TRUE(options.missingBlockIsIntegrityViolation().value()); } TEST_F(ProgramOptionsParserTest, MissingBlockIsIntegrityViolationGiven_False) { - ProgramOptions options = parse({"./myExecutable", basedir, "--missing-block-is-integrity-violation", "false", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--missing-block-is-integrity-violation", "false", mountdir}); EXPECT_FALSE(options.missingBlockIsIntegrityViolation().value()); } TEST_F(ProgramOptionsParserTest, AllowIntegrityViolations_True) { - ProgramOptions options = parse({"./myExecutable", basedir, "--allow-integrity-violations", mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, "--allow-integrity-violations", mountdir}); EXPECT_TRUE(options.allowIntegrityViolations()); } TEST_F(ProgramOptionsParserTest, AllowIntegrityViolations_False) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_FALSE(options.allowIntegrityViolations()); } TEST_F(ProgramOptionsParserTest, MissingBlockIsIntegrityViolationNotGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(none, options.missingBlockIsIntegrityViolation()); } TEST_F(ProgramOptionsParserTest, FuseOptionGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "--", "-f"}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "--", "-f"}); EXPECT_EQ(basedir, options.baseDir()); EXPECT_EQ(mountdir, options.mountDir()); EXPECT_VECTOR_EQ({"-f"}, options.fuseOptions()); } TEST_F(ProgramOptionsParserTest, FuseOptionGiven_Empty) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "--"}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "--"}); EXPECT_EQ(basedir, options.baseDir()); EXPECT_EQ(mountdir, options.mountDir()); EXPECT_VECTOR_EQ({}, options.fuseOptions()); } TEST_F(ProgramOptionsParserTest, FuseOptionNotGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir}); EXPECT_EQ(basedir, options.baseDir()); EXPECT_EQ(mountdir, options.mountDir()); EXPECT_VECTOR_EQ({}, options.fuseOptions()); } TEST_F(ProgramOptionsParserTest, DirectFuseOptionsGiven_AfterPositionalOptions) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "-o", "my_opt"}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "-o", "my_opt"}); EXPECT_VECTOR_EQ({"-o", "my_opt"}, options.fuseOptions()); } TEST_F(ProgramOptionsParserTest, DirectFuseOptionsGiven_BeforePositionalOptions) { - ProgramOptions options = parse({"./myExecutable", "-o", "my_opt", basedir, mountdir}); + const ProgramOptions options = parse({"./myExecutable", "-o", "my_opt", basedir, mountdir}); EXPECT_VECTOR_EQ({"-o", "my_opt"}, options.fuseOptions()); } TEST_F(ProgramOptionsParserTest, DirectFuseOptionsGiven_BeforeAndAfterPositionalOptions) { - ProgramOptions options = parse({"./myExecutable", "-o", "first", "-o", "second", basedir, "-o", "third", "-o", "fourth", mountdir, "-o", "fifth", "-o", "sixth"}); + const ProgramOptions options = parse({"./myExecutable", "-o", "first", "-o", "second", basedir, "-o", "third", "-o", "fourth", mountdir, "-o", "fifth", "-o", "sixth"}); EXPECT_VECTOR_EQ({"-o", "first", "-o", "second", "-o", "third", "-o", "fourth", "-o", "fifth", "-o", "sixth"}, options.fuseOptions()); } TEST_F(ProgramOptionsParserTest, DirectAndIndirectFuseOptionsGiven) { - ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "-o", "my_opt", "--", "-o", "other_opt"}); + const ProgramOptions options = parse({"./myExecutable", basedir, mountdir, "-o", "my_opt", "--", "-o", "other_opt"}); EXPECT_VECTOR_EQ({"-o", "other_opt", "-o", "my_opt"}, options.fuseOptions()); } diff --git a/test/cryfs-cli/program_options/ProgramOptionsTest.cpp b/test/cryfs-cli/program_options/ProgramOptionsTest.cpp index 6c96dce7..f104b34a 100644 --- a/test/cryfs-cli/program_options/ProgramOptionsTest.cpp +++ b/test/cryfs-cli/program_options/ProgramOptionsTest.cpp @@ -22,138 +22,138 @@ namespace boost { class ProgramOptionsTest: public ProgramOptionsTestBase {}; TEST_F(ProgramOptionsTest, BaseDir) { - ProgramOptions testobj("/home/user/mydir", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("/home/user/mydir", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ("/home/user/mydir", testobj.baseDir()); } TEST_F(ProgramOptionsTest, MountDir) { - ProgramOptions testobj("", "/home/user/mydir", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "/home/user/mydir", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ("/home/user/mydir", testobj.mountDir()); } TEST_F(ProgramOptionsTest, ConfigfileNone) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ(none, testobj.configFile()); } TEST_F(ProgramOptionsTest, ConfigfileSome) { - ProgramOptions testobj("", "", bf::path("/home/user/configfile"), true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", bf::path("/home/user/configfile"), true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ("/home/user/configfile", testobj.configFile().get()); } TEST_F(ProgramOptionsTest, ForegroundFalse) { - ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_FALSE(testobj.foreground()); } TEST_F(ProgramOptionsTest, ForegroundTrue) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_TRUE(testobj.foreground()); } TEST_F(ProgramOptionsTest, AllowFilesystemUpgradeFalse) { - ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_FALSE(testobj.allowFilesystemUpgrade()); } TEST_F(ProgramOptionsTest, AllowFilesystemUpgradeTrue) { - ProgramOptions testobj("", "", none, false, true, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, false, true, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_TRUE(testobj.allowFilesystemUpgrade()); } TEST_F(ProgramOptionsTest, CreateMissingBasedirFalse) { - ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_FALSE(testobj.createMissingBasedir()); } TEST_F(ProgramOptionsTest, CreateMissingBasedirTrue) { - ProgramOptions testobj("", "", none, false, true, false, true, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, false, true, false, true, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_TRUE(testobj.createMissingBasedir()); } TEST_F(ProgramOptionsTest, CreateMissingMountpointFalse) { - ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, false, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_FALSE(testobj.createMissingMountpoint()); } TEST_F(ProgramOptionsTest, CreateMissingMountpointTrue) { - ProgramOptions testobj("", "", none, false, true, false, false, true, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, false, true, false, false, true, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_TRUE(testobj.createMissingMountpoint()); } TEST_F(ProgramOptionsTest, LogfileNone) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ(none, testobj.logFile()); } TEST_F(ProgramOptionsTest, LogfileSome) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, bf::path("logfile"), none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, bf::path("logfile"), none, none, false, none, {"./myExecutable"}); EXPECT_EQ("logfile", testobj.logFile().get()); } TEST_F(ProgramOptionsTest, UnmountAfterIdleMinutesNone) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ(none, testobj.unmountAfterIdleMinutes()); } TEST_F(ProgramOptionsTest, UnmountAfterIdleMinutesSome) { - ProgramOptions testobj("", "", none, true, false, false, false, false, 10, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, 10, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ(10, testobj.unmountAfterIdleMinutes().get()); } TEST_F(ProgramOptionsTest, CipherNone) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ(none, testobj.cipher()); } TEST_F(ProgramOptionsTest, CipherSome) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, string("aes-256-gcm"), none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, string("aes-256-gcm"), none, false, none, {"./myExecutable"}); EXPECT_EQ("aes-256-gcm", testobj.cipher().get()); } TEST_F(ProgramOptionsTest, BlocksizeBytesNone) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ(none, testobj.blocksizeBytes()); } TEST_F(ProgramOptionsTest, BlocksizeBytesSome) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, 10*1024, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, 10*1024, false, none, {"./myExecutable"}); EXPECT_EQ(10*1024u, testobj.blocksizeBytes().get()); } TEST_F(ProgramOptionsTest, MissingBlockIsIntegrityViolationTrue) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, true, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, true, {"./myExecutable"}); EXPECT_TRUE(testobj.missingBlockIsIntegrityViolation().value()); } TEST_F(ProgramOptionsTest, MissingBlockIsIntegrityViolationFalse) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, false, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, false, {"./myExecutable"}); EXPECT_FALSE(testobj.missingBlockIsIntegrityViolation().value()); } TEST_F(ProgramOptionsTest, MissingBlockIsIntegrityViolationNone) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_EQ(none, testobj.missingBlockIsIntegrityViolation()); } TEST_F(ProgramOptionsTest, AllowIntegrityViolationsFalse) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, false, none, {"./myExecutable"}); EXPECT_FALSE(testobj.allowIntegrityViolations()); } TEST_F(ProgramOptionsTest, AllowIntegrityViolationsTrue) { - ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, true, none, {"./myExecutable"}); + const ProgramOptions testobj("", "", none, true, false, false, false, false, none, none, none, none, true, none, {"./myExecutable"}); EXPECT_TRUE(testobj.allowIntegrityViolations()); } TEST_F(ProgramOptionsTest, EmptyFuseOptions) { - ProgramOptions testobj("/rootDir", "/home/user/mydir", none, false, false, false, false, false, none, none, none, none, false, none, {}); + const ProgramOptions testobj("/rootDir", "/home/user/mydir", none, false, false, false, false, false, none, none, none, none, false, none, {}); //Fuse should have the mount dir as first parameter EXPECT_VECTOR_EQ({}, testobj.fuseOptions()); } TEST_F(ProgramOptionsTest, SomeFuseOptions) { - ProgramOptions testobj("/rootDir", "/home/user/mydir", none, false, false, false, false, false, none, none, none, none, false, none, {"-f", "--longoption"}); + const ProgramOptions testobj("/rootDir", "/home/user/mydir", none, false, false, false, false, false, none, none, none, none, false, none, {"-f", "--longoption"}); //Fuse should have the mount dir as first parameter EXPECT_VECTOR_EQ({"-f", "--longoption"}, testobj.fuseOptions()); } diff --git a/test/cryfs-cli/program_options/UtilsTest.cpp b/test/cryfs-cli/program_options/UtilsTest.cpp index b6fe53ed..05d020b9 100644 --- a/test/cryfs-cli/program_options/UtilsTest.cpp +++ b/test/cryfs-cli/program_options/UtilsTest.cpp @@ -9,106 +9,106 @@ using std::string; class ProgramOptionsUtilsTest: public ProgramOptionsTestBase {}; TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_ZeroOptions) { - vector input = {"./executableName"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName"}, result.first); EXPECT_VECTOR_EQ({}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OneShortOption) { - vector input = {"./executableName", "-j"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "-j"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "-j"}, result.first); EXPECT_VECTOR_EQ({}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OneLongOption) { - vector input = {"./executableName", "--myoption"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "--myoption"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "--myoption"}, result.first); EXPECT_VECTOR_EQ({}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OnePositionalOption) { - vector input = {"./executableName", "mypositionaloption"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "mypositionaloption"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "mypositionaloption"}, result.first); EXPECT_VECTOR_EQ({}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OneShortOption_DoubleDash) { - vector input = {"./executableName", "-j", "--"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "-j", "--"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "-j"}, result.first); EXPECT_VECTOR_EQ({}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OneLongOption_DoubleDash) { - vector input = {"./executableName", "--myoption", "--"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "--myoption", "--"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "--myoption"}, result.first); EXPECT_VECTOR_EQ({}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OnePositionalOption_DoubleDash) { - vector input = {"./executableName", "mypositionaloption", "--"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "mypositionaloption", "--"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "mypositionaloption"}, result.first); EXPECT_VECTOR_EQ({}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_DoubleDash_OneShortOption) { - vector input = {"./executableName", "--", "-a"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "--", "-a"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName"}, result.first); EXPECT_VECTOR_EQ({"-a"}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_DoubleDash_OneLongOption) { - vector input = {"./executableName", "--", "--myoption"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "--", "--myoption"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName"}, result.first); EXPECT_VECTOR_EQ({"--myoption"}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_DoubleDash_OnePositionalOption) { - vector input = {"./executableName", "--", "mypositionaloption"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "--", "mypositionaloption"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName"}, result.first); EXPECT_VECTOR_EQ({"mypositionaloption"}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OneShortOption_DoubleDash_OneShortOption) { - vector input = {"./executableName", "-j", "--", "-a"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "-j", "--", "-a"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "-j"}, result.first); EXPECT_VECTOR_EQ({"-a"}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OneLongOption_DoubleDash_OneLongOption) { - vector input = {"./executableName", "--myoption", "--", "--myotheroption"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "--myoption", "--", "--myotheroption"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "--myoption"}, result.first); EXPECT_VECTOR_EQ({"--myotheroption"}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_OnePositionalOption_DoubleDash_OnePositionalOption) { - vector input = {"./executableName", "mypositionaloption", "--", "otherpositionaloption"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "mypositionaloption", "--", "otherpositionaloption"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "mypositionaloption"}, result.first); EXPECT_VECTOR_EQ({"otherpositionaloption"}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_MoreOptions) { - vector input = {"./executableName", "mypositionaloption", "myotherpositionaloption", "-j", "--alpha", "--", "filename", "--beta", "-j3"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "mypositionaloption", "myotherpositionaloption", "-j", "--alpha", "--", "filename", "--beta", "-j3"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "mypositionaloption", "myotherpositionaloption", "-j", "--alpha"}, result.first); EXPECT_VECTOR_EQ({"filename", "--beta", "-j3"}, result.second); } TEST_F(ProgramOptionsUtilsTest, SplitAtDoubleDash_RealisticCryfsOptions) { - vector input = {"./executableName", "rootDir", "mountDir", "--", "-f"}; - pair,vector> result = splitAtDoubleDash(input); + const vector input = {"./executableName", "rootDir", "mountDir", "--", "-f"}; + const pair,vector> result = splitAtDoubleDash(input); EXPECT_VECTOR_EQ({"./executableName", "rootDir", "mountDir"}, result.first); EXPECT_VECTOR_EQ({"-f"}, result.second); } diff --git a/test/cryfs-cli/testutils/CliTest.h b/test/cryfs-cli/testutils/CliTest.h index 6ec7f374..66f9468b 100644 --- a/test/cryfs-cli/testutils/CliTest.h +++ b/test/cryfs-cli/testutils/CliTest.h @@ -62,7 +62,7 @@ public: } void EXPECT_RUN_ERROR(const std::vector& args, const std::string& message, cryfs::ErrorCode errorCode, std::function onMounted = [] {}) { - FilesystemOutput filesystem_output = run_filesystem(args, boost::none, std::move(onMounted)); + const FilesystemOutput filesystem_output = run_filesystem(args, boost::none, std::move(onMounted)); EXPECT_EQ(exitCode(errorCode), filesystem_output.exit_code); if (!std::regex_search(filesystem_output.stderr_, std::regex(message))) { @@ -77,7 +77,7 @@ public: bool successfully_mounted = false; - FilesystemOutput filesystem_output = run_filesystem(args, mountDir, [&] { + const FilesystemOutput filesystem_output = run_filesystem(args, mountDir, [&] { successfully_mounted = true; onMounted(); }); @@ -111,7 +111,7 @@ public: cpputils::ConditionBarrier isMountedOrFailedBarrier; std::future exit_code = std::async(std::launch::async, [&] { - int exit_code = run(args, [&] { isMountedOrFailedBarrier.release(); }); + const int exit_code = run(args, [&] { isMountedOrFailedBarrier.release(); }); // just in case it fails, we also want to release the barrier. // if it succeeds, this will release it a second time, which doesn't hurt. exited = true; diff --git a/test/cryfs/impl/config/CompatibilityTest.cpp b/test/cryfs/impl/config/CompatibilityTest.cpp index 07b931b3..8f74c583 100644 --- a/test/cryfs/impl/config/CompatibilityTest.cpp +++ b/test/cryfs/impl/config/CompatibilityTest.cpp @@ -42,7 +42,7 @@ private: ASSERT(hex.size()%2 == 0, "Hex codes need to have two characters per byte"); Data result(hex.size()/2); { - CryptoPP::StringSource _1(hex, true, + const CryptoPP::StringSource _1(hex, true, new CryptoPP::HexDecoder( new CryptoPP::ArraySink(static_cast(result.data()), result.size()) ) diff --git a/test/cryfs/impl/config/CryCipherTest.cpp b/test/cryfs/impl/config/CryCipherTest.cpp index 9c54e225..14eb2eca 100644 --- a/test/cryfs/impl/config/CryCipherTest.cpp +++ b/test/cryfs/impl/config/CryCipherTest.cpp @@ -37,15 +37,15 @@ public: void EXPECT_CREATES_CORRECT_ENCRYPTED_BLOCKSTORE(const string &cipherName) { const auto &actualCipher = CryCiphers::find(cipherName); Data dataFixture = DataFixture::generate(1024); - string encKey = ExpectedCipher::EncryptionKey::CreateKey(Random::PseudoRandom(), ExpectedCipher::KEYSIZE).ToString(); + const string encKey = ExpectedCipher::EncryptionKey::CreateKey(Random::PseudoRandom(), ExpectedCipher::KEYSIZE).ToString(); EXPECT_ENCRYPTS_WITH_ACTUAL_BLOCKSTORE_DECRYPTS_CORRECTLY_WITH_EXPECTED_BLOCKSTORE_(actualCipher, encKey, std::move(dataFixture)); } template void EXPECT_ENCRYPTS_WITH_ACTUAL_BLOCKSTORE_DECRYPTS_CORRECTLY_WITH_EXPECTED_BLOCKSTORE_(const CryCipher &actualCipher, const std::string &encKey, Data dataFixture) { - blockstore::BlockId blockId = blockstore::BlockId::Random(); + const blockstore::BlockId blockId = blockstore::BlockId::Random(); Data encrypted = _encryptUsingEncryptedBlockStoreWithCipher(actualCipher, encKey, blockId, dataFixture.copy()); - Data decrypted = _decryptUsingEncryptedBlockStoreWithCipher(encKey, blockId, std::move(encrypted)); + const Data decrypted = _decryptUsingEncryptedBlockStoreWithCipher(encKey, blockId, std::move(encrypted)); EXPECT_EQ(dataFixture, decrypted); } @@ -53,7 +53,7 @@ public: unique_ref _baseStore = make_unique_ref(); InMemoryBlockStore2 *baseStore = _baseStore.get(); unique_ref encryptedStore = cipher.createEncryptedBlockstore(std::move(_baseStore), encKey); - bool created = encryptedStore->tryCreate(blockId, data); + const bool created = encryptedStore->tryCreate(blockId, data); EXPECT_TRUE(created); return _loadBlock(baseStore, blockId); } @@ -61,7 +61,7 @@ public: template Data _decryptUsingEncryptedBlockStoreWithCipher(const std::string &encKey, const blockstore::BlockId &blockId, Data data) { unique_ref baseStore = make_unique_ref(); - bool created = baseStore->tryCreate(blockId, data); + const bool created = baseStore->tryCreate(blockId, data); EXPECT_TRUE(created); EncryptedBlockStore2 encryptedStore(std::move(baseStore), Cipher::EncryptionKey::FromString(encKey)); return _loadBlock(&encryptedStore, blockId); diff --git a/test/cryfs/impl/config/CryConfigConsoleTest.cpp b/test/cryfs/impl/config/CryConfigConsoleTest.cpp index 9d684732..3b6befb6 100644 --- a/test/cryfs/impl/config/CryConfigConsoleTest.cpp +++ b/test/cryfs/impl/config/CryConfigConsoleTest.cpp @@ -55,14 +55,14 @@ TEST_F(CryConfigConsoleTest_Cipher, AsksForCipher) { TEST_F(CryConfigConsoleTest_Cipher, ChooseDefaultCipher) { EXPECT_CALL(*console, askYesNo("Use default settings?", testing::_)).Times(1).WillOnce(Return(true)); EXPECT_CALL(*console, ask(HasSubstr("block cipher"), testing::_)).Times(0); - string cipher = cryconsole.askCipher(); + const string cipher = cryconsole.askCipher(); EXPECT_EQ(CryConfigConsole::DEFAULT_CIPHER, cipher); } TEST_F(CryConfigConsoleTest_Cipher, ChooseDefaultCipherWhenNoninteractiveEnvironment) { EXPECT_CALL(*console, askYesNo(HasSubstr("default"), testing::_)).Times(0); EXPECT_CALL(*console, ask(HasSubstr("block cipher"), testing::_)).Times(0); - string cipher = noninteractiveCryconsole.askCipher(); + const string cipher = noninteractiveCryconsole.askCipher(); EXPECT_EQ(CryConfigConsole::DEFAULT_CIPHER, cipher); } @@ -79,7 +79,7 @@ TEST_F(CryConfigConsoleTest_Cipher, AsksForMissingBlockIsIntegrityViolation) { TEST_F(CryConfigConsoleTest_Cipher, ChooseDefaultBlocksizeWhenNoninteractiveEnvironment) { EXPECT_CALL(*console, askYesNo(HasSubstr("default"), testing::_)).Times(0); EXPECT_CALL(*console, ask(HasSubstr("block size"), testing::_)).Times(0); - uint32_t blocksize = noninteractiveCryconsole.askBlocksizeBytes(); + const uint32_t blocksize = noninteractiveCryconsole.askBlocksizeBytes(); EXPECT_EQ(CryConfigConsole::DEFAULT_BLOCKSIZE_BYTES, blocksize); } @@ -106,7 +106,7 @@ TEST_P(CryConfigConsoleTest_Cipher_Choose, ChoosesCipherCorrectly) { EXPECT_ASK_FOR_CIPHER().WillOnce(ChooseCipher(cipherName)); - string chosenCipher = cryconsole.askCipher(); + const string chosenCipher = cryconsole.askCipher(); EXPECT_EQ(cipherName, chosenCipher); } diff --git a/test/cryfs/impl/config/CryConfigCreatorTest.cpp b/test/cryfs/impl/config/CryConfigCreatorTest.cpp index eeb42c5a..e59d8bd7 100644 --- a/test/cryfs/impl/config/CryConfigCreatorTest.cpp +++ b/test/cryfs/impl/config/CryConfigCreatorTest.cpp @@ -69,88 +69,88 @@ TEST_F(CryConfigCreatorTest, DoesAskForCipherIfNotSpecified) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); EXPECT_ASK_FOR_CIPHER().WillOnce(ChooseAnyCipher()); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskForCipherIfSpecified) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); EXPECT_DOES_NOT_ASK_FOR_CIPHER(); - CryConfig config = creator.create(string("aes-256-gcm"), none, none, false).config; + const CryConfig config = creator.create(string("aes-256-gcm"), none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskForCipherIfUsingDefaultSettings) { AnswerYesToDefaultSettings(); EXPECT_DOES_NOT_ASK_FOR_CIPHER(); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskForCipherIfNoninteractive) { EXPECT_DOES_NOT_ASK_TO_USE_DEFAULT_SETTINGS(); EXPECT_DOES_NOT_ASK_FOR_CIPHER(); - CryConfig config = noninteractiveCreator.create(none, none, none, false).config; + const CryConfig config = noninteractiveCreator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesAskForBlocksizeIfNotSpecified) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); EXPECT_ASK_FOR_BLOCKSIZE().WillOnce(Return(1)); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskForBlocksizeIfSpecified) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); EXPECT_DOES_NOT_ASK_FOR_BLOCKSIZE(); - CryConfig config = creator.create(none, 10*1024u, none, false).config; + const CryConfig config = creator.create(none, 10*1024u, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskForBlocksizeIfNoninteractive) { EXPECT_DOES_NOT_ASK_TO_USE_DEFAULT_SETTINGS(); EXPECT_DOES_NOT_ASK_FOR_BLOCKSIZE(); - CryConfig config = noninteractiveCreator.create(none, none, none, false).config; + const CryConfig config = noninteractiveCreator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskForBlocksizeIfUsingDefaultSettings) { AnswerYesToDefaultSettings(); EXPECT_DOES_NOT_ASK_FOR_BLOCKSIZE(); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesAskWhetherMissingBlocksAreIntegrityViolationsIfNotSpecified) { AnswerNoToDefaultSettings(); EXPECT_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION().WillOnce(Return(true)); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskWhetherMissingBlocksAreIntegrityViolationsIfSpecified_True) { AnswerNoToDefaultSettings(); EXPECT_DOES_NOT_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); - CryConfig config = creator.create(none, none, true, false).config; + const CryConfig config = creator.create(none, none, true, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskWhetherMissingBlocksAreIntegrityViolationsIfSpecified_False) { AnswerNoToDefaultSettings(); EXPECT_DOES_NOT_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); - CryConfig config = creator.create(none, none, false, false).config; + const CryConfig config = creator.create(none, none, false, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskWhetherMissingBlocksAreIntegrityViolationsIfNoninteractive) { EXPECT_DOES_NOT_ASK_TO_USE_DEFAULT_SETTINGS(); EXPECT_DOES_NOT_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); - CryConfig config = noninteractiveCreator.create(none, none, none, false).config; + const CryConfig config = noninteractiveCreator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, DoesNotAskWhetherMissingBlocksAreIntegrityViolationsIfUsingDefaultSettings) { AnswerYesToDefaultSettings(); EXPECT_DOES_NOT_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; } TEST_F(CryConfigCreatorTest, ChoosesEmptyRootBlobId) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; EXPECT_EQ("", config.RootBlob()); // This tells CryFS to create a new root blob } @@ -158,7 +158,7 @@ TEST_F(CryConfigCreatorTest, ChoosesValidEncryptionKey_448) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); EXPECT_ASK_FOR_CIPHER().WillOnce(ChooseCipher("mars-448-gcm")); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; cpputils::Mars448_GCM::EncryptionKey::FromString(config.EncryptionKey()); // This crashes if invalid } @@ -166,7 +166,7 @@ TEST_F(CryConfigCreatorTest, ChoosesValidEncryptionKey_256) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); EXPECT_ASK_FOR_CIPHER().WillOnce(ChooseCipher("aes-256-gcm")); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; cpputils::AES256_GCM::EncryptionKey::FromString(config.EncryptionKey()); // This crashes if invalid } @@ -174,28 +174,28 @@ TEST_F(CryConfigCreatorTest, ChoosesValidEncryptionKey_128) { AnswerNoToDefaultSettings(); IGNORE_ASK_FOR_MISSINGBLOCKISINTEGRITYVIOLATION(); EXPECT_ASK_FOR_CIPHER().WillOnce(ChooseCipher("aes-128-gcm")); - CryConfig config = creator.create(none, none, none, false).config; + const CryConfig config = creator.create(none, none, none, false).config; cpputils::AES128_GCM::EncryptionKey::FromString(config.EncryptionKey()); // This crashes if invalid } TEST_F(CryConfigCreatorTest, DoesNotAskForAnythingIfEverythingIsSpecified) { EXPECT_DOES_NOT_ASK_TO_USE_DEFAULT_SETTINGS(); EXPECT_DOES_NOT_ASK_FOR_CIPHER(); - CryConfig config = noninteractiveCreator.create(string("aes-256-gcm"), 10*1024u, none, false).config; + const CryConfig config = noninteractiveCreator.create(string("aes-256-gcm"), 10*1024u, none, false).config; } TEST_F(CryConfigCreatorTest, SetsCorrectCreatedWithVersion) { - CryConfig config = noninteractiveCreator.create(none, none, none, false).config; + const CryConfig config = noninteractiveCreator.create(none, none, none, false).config; EXPECT_EQ(gitversion::VersionString(), config.CreatedWithVersion()); } TEST_F(CryConfigCreatorTest, SetsCorrectLastOpenedWithVersion) { - CryConfig config = noninteractiveCreator.create(none, none, none, false).config; + const CryConfig config = noninteractiveCreator.create(none, none, none, false).config; EXPECT_EQ(gitversion::VersionString(), config.CreatedWithVersion()); } TEST_F(CryConfigCreatorTest, SetsCorrectVersion) { - CryConfig config = noninteractiveCreator.create(none, none, none, false).config; + const CryConfig config = noninteractiveCreator.create(none, none, none, false).config; EXPECT_EQ(CryConfig::FilesystemFormatVersion, config.Version()); } diff --git a/test/cryfs/impl/config/CryConfigFileTest.cpp b/test/cryfs/impl/config/CryConfigFileTest.cpp index c43ca34c..c6272933 100644 --- a/test/cryfs/impl/config/CryConfigFileTest.cpp +++ b/test/cryfs/impl/config/CryConfigFileTest.cpp @@ -177,8 +177,8 @@ TEST_F(CryConfigFileTest, CreatedWithVersion_SaveAndLoad) { //Test that the encrypted config file has the same size, no matter how big the plaintext config data. TEST_F(CryConfigFileTest, ConfigFileHasFixedSize) { - TempFile file1(false); - TempFile file2(false); + const TempFile file1(false); + const TempFile file2(false); //It is important to have different cipher name lengths here, because they're on the outer encryption level. //So this ensures that there also is a padding happening on the outer encryption level. CreateWithCipher("aes-128-gcm", file1); // Short cipher name and short key @@ -202,7 +202,7 @@ TEST_F(CryConfigFileTest, FailsIfConfigFileIsEncryptedWithACipherDifferentToTheO auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider); auto config = Config(); config.SetCipher("aes-256-gcm"); - Data encrypted = encryptor->encrypt(config.save(), "aes-256-cfb"); + const Data encrypted = encryptor->encrypt(config.save(), "aes-256-cfb"); encrypted.StoreToFile(file.path()); auto loaded = Load(keySeed); EXPECT_EQ(none, loaded); diff --git a/test/cryfs/impl/config/CryConfigLoaderTest.cpp b/test/cryfs/impl/config/CryConfigLoaderTest.cpp index ec1ea1f4..671bb748 100644 --- a/test/cryfs/impl/config/CryConfigLoaderTest.cpp +++ b/test/cryfs/impl/config/CryConfigLoaderTest.cpp @@ -315,7 +315,7 @@ TEST_F(CryConfigLoaderTest, FilesystemID_Create) { TEST_F(CryConfigLoaderTest, AsksWhenLoadingNewerFilesystem_AnswerYes) { EXPECT_CALL(*console, askYesNo(HasSubstr("should not be opened with older versions"), false)).Times(1).WillOnce(Return(true)); - string version = newerVersion(); + const string version = newerVersion(); CreateWithVersion(version, version); EXPECT_TRUE(LoadOrCreate().is_right()); } @@ -323,7 +323,7 @@ TEST_F(CryConfigLoaderTest, AsksWhenLoadingNewerFilesystem_AnswerYes) { TEST_F(CryConfigLoaderTest, AsksWhenLoadingNewerFilesystem_AnswerNo) { EXPECT_CALL(*console, askYesNo(HasSubstr("should not be opened with older versions"), false)).Times(1).WillOnce(Return(false)); - string version = newerVersion(); + const string version = newerVersion(); CreateWithVersion(version, version); try { LoadOrCreate(); @@ -336,7 +336,7 @@ TEST_F(CryConfigLoaderTest, AsksWhenLoadingNewerFilesystem_AnswerNo) { TEST_F(CryConfigLoaderTest, AsksWhenMigratingOlderFilesystem) { EXPECT_CALL(*console, askYesNo(HasSubstr("Do you want to attempt a migration now?"), false)).Times(1).WillOnce(Return(true)); - string version = olderVersion(); + const string version = olderVersion(); CreateWithVersion(version, version); EXPECT_TRUE(LoadOrCreate().is_right()); } @@ -351,7 +351,7 @@ TEST_F(CryConfigLoaderTest, DoesNotAskForMigrationWhenCorrectVersion) { TEST_F(CryConfigLoaderTest, DontMigrateWhenAnsweredNo) { EXPECT_CALL(*console, askYesNo(HasSubstr("Do you want to attempt a migration now?"), false)).Times(1).WillOnce(Return(false)); - string version = olderVersion(); + const string version = olderVersion(); CreateWithVersion(version, version); try { LoadOrCreate(); @@ -362,22 +362,22 @@ TEST_F(CryConfigLoaderTest, DontMigrateWhenAnsweredNo) { } TEST_F(CryConfigLoaderTest, MyClientIdIsIndeterministic) { - TempFile file1(false); - TempFile file2(false); - uint32_t myClientId = loader("mypassword", true).loadOrCreate(file1.path(), false, false).right().myClientId; + const TempFile file1(false); + const TempFile file2(false); + const uint32_t myClientId = loader("mypassword", true).loadOrCreate(file1.path(), false, false).right().myClientId; EXPECT_NE(myClientId, loader("mypassword", true).loadOrCreate(file2.path(), false, false).right().myClientId); } TEST_F(CryConfigLoaderTest, MyClientIdIsLoadedCorrectly) { - TempFile file(false); - uint32_t myClientId = loader("mypassword", true).loadOrCreate(file.path(), false, false).right().myClientId; + const TempFile file(false); + const uint32_t myClientId = loader("mypassword", true).loadOrCreate(file.path(), false, false).right().myClientId; EXPECT_EQ(myClientId, loader("mypassword", true).loadOrCreate(file.path(), false, false).right().myClientId); } TEST_F(CryConfigLoaderTest, DoesNotAskForMigrationWhenUpgradesAllowedByProgramArguments_NoninteractiveMode) { EXPECT_CALL(*console, askYesNo(HasSubstr("migrate"), testing::_)).Times(0); - string version = olderVersion(); + const string version = olderVersion(); CreateWithVersion(version, version); EXPECT_TRUE(LoadOrCreate("mypassword", none, true, true).is_right()); } @@ -385,7 +385,7 @@ TEST_F(CryConfigLoaderTest, DoesNotAskForMigrationWhenUpgradesAllowedByProgramAr TEST_F(CryConfigLoaderTest, DoesNotAskForMigrationWhenUpgradesAllowedByProgramArguments_InteractiveMode) { EXPECT_CALL(*console, askYesNo(HasSubstr("migrate"), testing::_)).Times(0); - string version = olderVersion(); + const string version = olderVersion(); CreateWithVersion(version, version); EXPECT_TRUE(LoadOrCreate("mypassword", none, false, true).is_right()); } @@ -393,7 +393,7 @@ TEST_F(CryConfigLoaderTest, DoesNotAskForMigrationWhenUpgradesAllowedByProgramAr TEST_F(CryConfigLoaderTest, UpdatesConfigFileWithNewVersionWhenMigrated) { EXPECT_CALL(*console, askYesNo(HasSubstr("Do you want to attempt a migration now?"), false)).Times(1).WillOnce(Return(true)); - string version = olderVersion(); // this triggers a migration which should cause it to modify the config file on load + const string version = olderVersion(); // this triggers a migration which should cause it to modify the config file on load CreateWithVersion(version, version); expectLoadingModifiesFile(CryConfigFile::Access::ReadWrite); @@ -405,7 +405,7 @@ TEST_F(CryConfigLoaderTest, UpdatesConfigFileWithNewVersionWhenMigrated) { TEST_F(CryConfigLoaderTest, DoesntUpdatesConfigFileWithNewVersionWhenLoadingReadOnly) { EXPECT_CALL(*console, askYesNo(HasSubstr("Do you want to attempt a migration now?"), false)).Times(1).WillOnce(Return(true)); - string version = olderVersion(); // this triggers a migration which usually would cause it to modify the config file on load + const string version = olderVersion(); // this triggers a migration which usually would cause it to modify the config file on load CreateWithVersion(version, version); expectLoadingDoesntModifyFile(CryConfigFile::Access::ReadOnly); diff --git a/test/cryfs/impl/config/CryConfigTest.cpp b/test/cryfs/impl/config/CryConfigTest.cpp index 83ef5fc2..1bb8df6b 100644 --- a/test/cryfs/impl/config/CryConfigTest.cpp +++ b/test/cryfs/impl/config/CryConfigTest.cpp @@ -3,6 +3,8 @@ #include #include +#include + using namespace cryfs; using cpputils::Data; using cpputils::DataFixture; @@ -13,7 +15,7 @@ public: CryConfig cfg; CryConfig SaveAndLoad(CryConfig cfg) { - Data configData = cfg.save(); + const Data configData = cfg.save(); return CryConfig::load(configData); } }; @@ -29,19 +31,19 @@ TEST_F(CryConfigTest, RootBlob) { TEST_F(CryConfigTest, RootBlob_AfterMove) { cfg.SetRootBlob("rootblobid"); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ("rootblobid", moved.RootBlob()); } TEST_F(CryConfigTest, RootBlob_AfterCopy) { cfg.SetRootBlob("rootblobid"); - CryConfig copy = cfg; + const CryConfig copy = cfg; EXPECT_EQ("rootblobid", copy.RootBlob()); } TEST_F(CryConfigTest, RootBlob_AfterSaveAndLoad) { cfg.SetRootBlob("rootblobid"); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ("rootblobid", loaded.RootBlob()); } @@ -56,19 +58,19 @@ TEST_F(CryConfigTest, EncryptionKey) { TEST_F(CryConfigTest, EncryptionKey_AfterMove) { cfg.SetEncryptionKey("enckey"); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ("enckey", moved.EncryptionKey()); } TEST_F(CryConfigTest, EncryptionKey_AfterCopy) { cfg.SetEncryptionKey("enckey"); - CryConfig copy = cfg; + const CryConfig copy = cfg; EXPECT_EQ("enckey", copy.EncryptionKey()); } TEST_F(CryConfigTest, EncryptionKey_AfterSaveAndLoad) { cfg.SetEncryptionKey("enckey"); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ("enckey", loaded.EncryptionKey()); } @@ -83,19 +85,19 @@ TEST_F(CryConfigTest, Cipher) { TEST_F(CryConfigTest, Cipher_AfterMove) { cfg.SetCipher("mycipher"); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ("mycipher", moved.Cipher()); } TEST_F(CryConfigTest, Cipher_AfterCopy) { cfg.SetCipher("mycipher"); - CryConfig copy = cfg; + const CryConfig copy = cfg; EXPECT_EQ("mycipher", copy.Cipher()); } TEST_F(CryConfigTest, Cipher_AfterSaveAndLoad) { cfg.SetCipher("mycipher"); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ("mycipher", loaded.Cipher()); } @@ -110,19 +112,19 @@ TEST_F(CryConfigTest, Version) { TEST_F(CryConfigTest, Version_AfterMove) { cfg.SetVersion("0.9.1"); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ("0.9.1", moved.Version()); } TEST_F(CryConfigTest, Version_AfterCopy) { cfg.SetVersion("0.9.1"); - CryConfig copy = cfg; + const CryConfig copy = cfg; EXPECT_EQ("0.9.1", copy.Version()); } TEST_F(CryConfigTest, Version_AfterSaveAndLoad) { cfg.SetVersion("0.9.2"); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ("0.9.2", loaded.Version()); } @@ -137,19 +139,19 @@ TEST_F(CryConfigTest, CreatedWithVersion) { TEST_F(CryConfigTest, CreatedWithVersion_AfterMove) { cfg.SetCreatedWithVersion("0.9.3"); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ("0.9.3", moved.CreatedWithVersion()); } TEST_F(CryConfigTest, CreatedWithVersion_AfterCopy) { cfg.SetCreatedWithVersion("0.9.3"); - CryConfig copy = cfg; + const CryConfig copy = cfg; EXPECT_EQ("0.9.3", copy.CreatedWithVersion()); } TEST_F(CryConfigTest, CreatedWithVersion_AfterSaveAndLoad) { cfg.SetCreatedWithVersion("0.9.3"); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ("0.9.3", loaded.CreatedWithVersion()); } @@ -164,19 +166,19 @@ TEST_F(CryConfigTest, BlocksizeBytes) { TEST_F(CryConfigTest, BlocksizeBytes_AfterMove) { cfg.SetBlocksizeBytes(32*1024); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ(32*1024u, moved.BlocksizeBytes()); } TEST_F(CryConfigTest, BlocksizeBytes_AfterCopy) { cfg.SetBlocksizeBytes(32*1024); - CryConfig copy = cfg; + const CryConfig copy = cfg; EXPECT_EQ(32*1024u, copy.BlocksizeBytes()); } TEST_F(CryConfigTest, BlocksizeBytes_AfterSaveAndLoad) { cfg.SetBlocksizeBytes(10*1024); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ(10*1024u, loaded.BlocksizeBytes()); } @@ -193,14 +195,14 @@ TEST_F(CryConfigTest, FilesystemID) { TEST_F(CryConfigTest, FilesystemID_AfterMove) { auto fixture = DataFixture::generateFixedSize(); cfg.SetFilesystemId(fixture); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ(fixture, moved.FilesystemId()); } TEST_F(CryConfigTest, FilesystemID_AfterSaveAndLoad) { auto fixture = DataFixture::generateFixedSize(); cfg.SetFilesystemId(fixture); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ(fixture, loaded.FilesystemId()); } @@ -221,25 +223,25 @@ TEST_F(CryConfigTest, ExclusiveClientId_None) { TEST_F(CryConfigTest, ExclusiveClientId_Some_AfterMove) { cfg.SetExclusiveClientId(0x12345678u); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ(0x12345678u, moved.ExclusiveClientId().value()); } TEST_F(CryConfigTest, ExclusiveClientId_None_AfterMove) { cfg.SetExclusiveClientId(0x12345678u); cfg.SetExclusiveClientId(none); - CryConfig moved = std::move(cfg); + const CryConfig moved = std::move(cfg); EXPECT_EQ(none, moved.ExclusiveClientId()); } TEST_F(CryConfigTest, ExclusiveClientId_Some_AfterSaveAndLoad) { cfg.SetExclusiveClientId(0x12345678u); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ(0x12345678u, loaded.ExclusiveClientId().value()); } TEST_F(CryConfigTest, ExclusiveClientId_None_AfterSaveAndLoad) { cfg.SetExclusiveClientId(none); - CryConfig loaded = SaveAndLoad(std::move(cfg)); + const CryConfig loaded = SaveAndLoad(std::move(cfg)); EXPECT_EQ(none, loaded.ExclusiveClientId()); } diff --git a/test/cryfs/impl/config/CryPasswordBasedKeyProviderTest.cpp b/test/cryfs/impl/config/CryPasswordBasedKeyProviderTest.cpp index 2bcde410..cdf8c429 100644 --- a/test/cryfs/impl/config/CryPasswordBasedKeyProviderTest.cpp +++ b/test/cryfs/impl/config/CryPasswordBasedKeyProviderTest.cpp @@ -80,7 +80,7 @@ TEST_F(CryPasswordBasedKeyProviderTest, requestKeyForExistingFilesystem) { return key; })); - EncryptionKey returned_key = keyProvider.requestKeyForExistingFilesystem(keySize, kdfParameters); + const EncryptionKey returned_key = keyProvider.requestKeyForExistingFilesystem(keySize, kdfParameters); EXPECT_EQ(key.ToString(), returned_key.ToString()); } diff --git a/test/cryfs/impl/config/CryPresetPasswordBasedKeyProviderTest.cpp b/test/cryfs/impl/config/CryPresetPasswordBasedKeyProviderTest.cpp index b8b7a9d2..21fcd826 100644 --- a/test/cryfs/impl/config/CryPresetPasswordBasedKeyProviderTest.cpp +++ b/test/cryfs/impl/config/CryPresetPasswordBasedKeyProviderTest.cpp @@ -51,7 +51,7 @@ TEST(CryPresetPasswordBasedKeyProviderTest, requestKeyForExistingFilesystem) { })); CryPresetPasswordBasedKeyProvider keyProvider(password, std::move(kdf)); - EncryptionKey returned_key = keyProvider.requestKeyForExistingFilesystem(keySize, kdfParameters); + const EncryptionKey returned_key = keyProvider.requestKeyForExistingFilesystem(keySize, kdfParameters); EXPECT_EQ(key.ToString(), returned_key.ToString()); } diff --git a/test/cryfs/impl/config/crypto/CryConfigEncryptorFactoryTest.cpp b/test/cryfs/impl/config/crypto/CryConfigEncryptorFactoryTest.cpp index 661a3028..3bd206e3 100644 --- a/test/cryfs/impl/config/crypto/CryConfigEncryptorFactoryTest.cpp +++ b/test/cryfs/impl/config/crypto/CryConfigEncryptorFactoryTest.cpp @@ -26,7 +26,7 @@ public: TEST_F(CryConfigEncryptorFactoryTest, EncryptAndDecrypt_SameEncryptor) { FakeCryKeyProvider keyProvider; auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider); - Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); + const Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); auto decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(DataFixture::generate(400), decrypted.data); } @@ -34,7 +34,7 @@ TEST_F(CryConfigEncryptorFactoryTest, EncryptAndDecrypt_SameEncryptor) { TEST_F(CryConfigEncryptorFactoryTest, EncryptAndDecrypt_NewEncryptor) { FakeCryKeyProvider keyProvider1(1); auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider1); - Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); + const Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); FakeCryKeyProvider keyProvider2(1); auto loadedEncryptor = CryConfigEncryptorFactory::loadExistingKey(encrypted, &keyProvider2).value(); @@ -45,7 +45,7 @@ TEST_F(CryConfigEncryptorFactoryTest, EncryptAndDecrypt_NewEncryptor) { TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptWithWrongKey) { FakeCryKeyProvider keyProvider1(1); auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider1); - Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); + const Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); FakeCryKeyProvider keyProvider2(2); auto loadedEncryptor = CryConfigEncryptorFactory::loadExistingKey(encrypted, &keyProvider2).value(); @@ -56,7 +56,7 @@ TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptWithWrongKey) { TEST_F(CryConfigEncryptorFactoryTest, DoesntDecryptWithWrongKey_EmptyData) { FakeCryKeyProvider keyProvider1(1); auto encryptor = CryConfigEncryptorFactory::deriveNewKey(&keyProvider1); - Data encrypted = encryptor->encrypt(Data(0), AES256_GCM::NAME); + const Data encrypted = encryptor->encrypt(Data(0), AES256_GCM::NAME); FakeCryKeyProvider keyProvider2(2); auto loadedEncryptor = CryConfigEncryptorFactory::loadExistingKey(encrypted, &keyProvider2).value(); diff --git a/test/cryfs/impl/config/crypto/CryConfigEncryptorTest.cpp b/test/cryfs/impl/config/crypto/CryConfigEncryptorTest.cpp index d657ed36..bb5ef0e0 100644 --- a/test/cryfs/impl/config/crypto/CryConfigEncryptorTest.cpp +++ b/test/cryfs/impl/config/crypto/CryConfigEncryptorTest.cpp @@ -56,49 +56,49 @@ private: } InnerConfig _decryptInnerConfig(const Data &data) { - OuterConfig outerConfig = OuterConfig::deserialize(data).value(); - Data serializedInnerConfig = _outerEncryptor()->decrypt(outerConfig).value(); + const OuterConfig outerConfig = OuterConfig::deserialize(data).value(); + const Data serializedInnerConfig = _outerEncryptor()->decrypt(outerConfig).value(); return InnerConfig::deserialize(serializedInnerConfig).value(); } Data _encryptInnerConfig(const InnerConfig &innerConfig) { - Data serializedInnerConfig = innerConfig.serialize(); - OuterConfig outerConfig = _outerEncryptor()->encrypt(serializedInnerConfig); + const Data serializedInnerConfig = innerConfig.serialize(); + const OuterConfig outerConfig = _outerEncryptor()->encrypt(serializedInnerConfig); return outerConfig.serialize(); } }; TEST_F(CryConfigEncryptorTest, EncryptAndDecrypt_Data_AES) { auto encryptor = makeEncryptor(); - Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); + const Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); auto decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(DataFixture::generate(400), decrypted.data); } TEST_F(CryConfigEncryptorTest, EncryptAndDecrypt_Data_Twofish) { auto encryptor = makeEncryptor(); - Data encrypted = encryptor->encrypt(DataFixture::generate(400), Twofish128_CFB::NAME); + const Data encrypted = encryptor->encrypt(DataFixture::generate(400), Twofish128_CFB::NAME); auto decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(DataFixture::generate(400), decrypted.data); } TEST_F(CryConfigEncryptorTest, EncryptAndDecrypt_Cipher_AES) { auto encryptor = makeEncryptor(); - Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); + const Data encrypted = encryptor->encrypt(DataFixture::generate(400), AES256_GCM::NAME); auto decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(AES256_GCM::NAME, decrypted.cipherName); } TEST_F(CryConfigEncryptorTest, EncryptAndDecrypt_Cipher_Twofish) { auto encryptor = makeEncryptor(); - Data encrypted = encryptor->encrypt(DataFixture::generate(400), Twofish128_CFB::NAME); + const Data encrypted = encryptor->encrypt(DataFixture::generate(400), Twofish128_CFB::NAME); auto decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(Twofish128_CFB::NAME, decrypted.cipherName); } TEST_F(CryConfigEncryptorTest, EncryptAndDecrypt_EmptyData) { auto encryptor = makeEncryptor(); - Data encrypted = encryptor->encrypt(Data(0), AES256_GCM::NAME); + const Data encrypted = encryptor->encrypt(Data(0), AES256_GCM::NAME); auto decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(Data(0), decrypted.data); } @@ -121,9 +121,9 @@ TEST_F(CryConfigEncryptorTest, DoesntEncryptWhenTooLarge) { TEST_F(CryConfigEncryptorTest, EncryptionIsFixedSize) { auto encryptor = makeEncryptor(); - Data encrypted1 = encryptor->encrypt(DataFixture::generate(100), AES128_CFB::NAME); - Data encrypted2 = encryptor->encrypt(DataFixture::generate(200), Twofish256_GCM::NAME); - Data encrypted3 = encryptor->encrypt(Data(0), AES256_GCM::NAME); + const Data encrypted1 = encryptor->encrypt(DataFixture::generate(100), AES128_CFB::NAME); + const Data encrypted2 = encryptor->encrypt(DataFixture::generate(200), Twofish256_GCM::NAME); + const Data encrypted3 = encryptor->encrypt(Data(0), AES256_GCM::NAME); EXPECT_EQ(encrypted1.size(), encrypted2.size()); EXPECT_EQ(encrypted1.size(), encrypted3.size()); diff --git a/test/cryfs/impl/config/crypto/inner/ConcreteInnerEncryptorTest.cpp b/test/cryfs/impl/config/crypto/inner/ConcreteInnerEncryptorTest.cpp index 6157e790..a28a4d7c 100644 --- a/test/cryfs/impl/config/crypto/inner/ConcreteInnerEncryptorTest.cpp +++ b/test/cryfs/impl/config/crypto/inner/ConcreteInnerEncryptorTest.cpp @@ -37,22 +37,22 @@ public: TEST_F(ConcreteInnerEncryptorTest, EncryptAndDecrypt_AES) { auto encryptor = makeInnerEncryptor(); - InnerConfig encrypted = encryptor->encrypt(DataFixture::generate(200)); - Data decrypted = encryptor->decrypt(encrypted).value(); + const InnerConfig encrypted = encryptor->encrypt(DataFixture::generate(200)); + const Data decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(DataFixture::generate(200), decrypted); } TEST_F(ConcreteInnerEncryptorTest, EncryptAndDecrypt_Twofish) { auto encryptor = makeInnerEncryptor(); - InnerConfig encrypted = encryptor->encrypt(DataFixture::generate(200)); - Data decrypted = encryptor->decrypt(encrypted).value(); + const InnerConfig encrypted = encryptor->encrypt(DataFixture::generate(200)); + const Data decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(DataFixture::generate(200), decrypted); } TEST_F(ConcreteInnerEncryptorTest, EncryptAndDecrypt_EmptyData) { auto encryptor = makeInnerEncryptor(); - InnerConfig encrypted = encryptor->encrypt(Data(0)); - Data decrypted = encryptor->decrypt(encrypted).value(); + const InnerConfig encrypted = encryptor->encrypt(Data(0)); + const Data decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(Data(0), decrypted); } @@ -82,9 +82,9 @@ TEST_F(ConcreteInnerEncryptorTest, DoesntEncryptWhenTooLarge) { TEST_F(ConcreteInnerEncryptorTest, EncryptionIsFixedSize) { auto encryptor = makeInnerEncryptor(); - InnerConfig encrypted1 = encryptor->encrypt(DataFixture::generate(100)); - InnerConfig encrypted2 = encryptor->encrypt(DataFixture::generate(200)); - InnerConfig encrypted3 = encryptor->encrypt(Data(0)); + const InnerConfig encrypted1 = encryptor->encrypt(DataFixture::generate(100)); + const InnerConfig encrypted2 = encryptor->encrypt(DataFixture::generate(200)); + const InnerConfig encrypted3 = encryptor->encrypt(Data(0)); EXPECT_EQ(encrypted1.encryptedConfig.size(), encrypted2.encryptedConfig.size()); EXPECT_EQ(encrypted1.encryptedConfig.size(), encrypted3.encryptedConfig.size()); diff --git a/test/cryfs/impl/config/crypto/inner/InnerConfigTest.cpp b/test/cryfs/impl/config/crypto/inner/InnerConfigTest.cpp index 3f1ebcac..ec11c87f 100644 --- a/test/cryfs/impl/config/crypto/inner/InnerConfigTest.cpp +++ b/test/cryfs/impl/config/crypto/inner/InnerConfigTest.cpp @@ -17,29 +17,29 @@ namespace boost { #include TEST(InnerConfigTest, SomeValues) { - Data serialized = InnerConfig{"myciphername", DataFixture::generate(1024)}.serialize(); - InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); + const Data serialized = InnerConfig{"myciphername", DataFixture::generate(1024)}.serialize(); + const InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); EXPECT_EQ("myciphername", deserialized.cipherName); EXPECT_EQ(DataFixture::generate(1024), deserialized.encryptedConfig); } TEST(InnerConfigTest, DataEmpty) { - Data serialized = InnerConfig{"myciphername", Data(0)}.serialize(); - InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); + const Data serialized = InnerConfig{"myciphername", Data(0)}.serialize(); + const InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); EXPECT_EQ("myciphername", deserialized.cipherName); EXPECT_EQ(Data(0), deserialized.encryptedConfig); } TEST(InnerConfigTest, CipherNameEmpty) { - Data serialized = InnerConfig{"", DataFixture::generate(1024)}.serialize(); - InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); + const Data serialized = InnerConfig{"", DataFixture::generate(1024)}.serialize(); + const InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); EXPECT_EQ("", deserialized.cipherName); EXPECT_EQ(DataFixture::generate(1024), deserialized.encryptedConfig); } TEST(InnerConfigTest, DataAndCipherNameEmpty) { - Data serialized = InnerConfig{"", Data(0)}.serialize(); - InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); + const Data serialized = InnerConfig{"", Data(0)}.serialize(); + const InnerConfig deserialized = InnerConfig::deserialize(serialized).value(); EXPECT_EQ("", deserialized.cipherName); EXPECT_EQ(Data(0), deserialized.encryptedConfig); } diff --git a/test/cryfs/impl/config/crypto/outer/OuterConfigTest.cpp b/test/cryfs/impl/config/crypto/outer/OuterConfigTest.cpp index ba2068b0..8fcc8866 100644 --- a/test/cryfs/impl/config/crypto/outer/OuterConfigTest.cpp +++ b/test/cryfs/impl/config/crypto/outer/OuterConfigTest.cpp @@ -24,29 +24,29 @@ public: }; TEST_F(OuterConfigTest, SomeValues) { - Data serialized = OuterConfig{kdfParameters(), DataFixture::generate(1024), false}.serialize(); - OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); + const Data serialized = OuterConfig{kdfParameters(), DataFixture::generate(1024), false}.serialize(); + const OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); EXPECT_EQ(kdfParameters(), deserialized.kdfParameters); EXPECT_EQ(DataFixture::generate(1024), deserialized.encryptedInnerConfig); } TEST_F(OuterConfigTest, DataEmpty) { - Data serialized = OuterConfig{kdfParameters(), Data(0), false}.serialize(); - OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); + const Data serialized = OuterConfig{kdfParameters(), Data(0), false}.serialize(); + const OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); EXPECT_EQ(kdfParameters(), deserialized.kdfParameters); EXPECT_EQ(Data(0), deserialized.encryptedInnerConfig); } TEST_F(OuterConfigTest, KeyConfigEmpty) { - Data serialized = OuterConfig{Data(0), DataFixture::generate(1024), false}.serialize(); - OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); + const Data serialized = OuterConfig{Data(0), DataFixture::generate(1024), false}.serialize(); + const OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); EXPECT_EQ(Data(0), deserialized.kdfParameters); EXPECT_EQ(DataFixture::generate(1024), deserialized.encryptedInnerConfig); } TEST_F(OuterConfigTest, DataAndKeyConfigEmpty) { - Data serialized = OuterConfig{Data(0), Data(0), false}.serialize(); - OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); + const Data serialized = OuterConfig{Data(0), Data(0), false}.serialize(); + const OuterConfig deserialized = OuterConfig::deserialize(serialized).value(); EXPECT_EQ(Data(0), deserialized.kdfParameters); EXPECT_EQ(Data(0), deserialized.encryptedInnerConfig); } diff --git a/test/cryfs/impl/config/crypto/outer/OuterEncryptorTest.cpp b/test/cryfs/impl/config/crypto/outer/OuterEncryptorTest.cpp index 412fc726..8b3c245a 100644 --- a/test/cryfs/impl/config/crypto/outer/OuterEncryptorTest.cpp +++ b/test/cryfs/impl/config/crypto/outer/OuterEncryptorTest.cpp @@ -37,15 +37,15 @@ public: TEST_F(OuterEncryptorTest, EncryptAndDecrypt) { auto encryptor = makeOuterEncryptor(); - OuterConfig encrypted = encryptor->encrypt(DataFixture::generate(200)); - Data decrypted = encryptor->decrypt(encrypted).value(); + const OuterConfig encrypted = encryptor->encrypt(DataFixture::generate(200)); + const Data decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(DataFixture::generate(200), decrypted); } TEST_F(OuterEncryptorTest, EncryptAndDecrypt_EmptyData) { auto encryptor = makeOuterEncryptor(); - OuterConfig encrypted = encryptor->encrypt(Data(0)); - Data decrypted = encryptor->decrypt(encrypted).value(); + const OuterConfig encrypted = encryptor->encrypt(Data(0)); + const Data decrypted = encryptor->decrypt(encrypted).value(); EXPECT_EQ(Data(0), decrypted); } @@ -67,9 +67,9 @@ TEST_F(OuterEncryptorTest, DoesntEncryptWhenTooLarge) { TEST_F(OuterEncryptorTest, EncryptionIsFixedSize) { auto encryptor = makeOuterEncryptor(); - OuterConfig encrypted1 = encryptor->encrypt(DataFixture::generate(200)); - OuterConfig encrypted2 = encryptor->encrypt(DataFixture::generate(700)); - OuterConfig encrypted3 = encryptor->encrypt(Data(0)); + const OuterConfig encrypted1 = encryptor->encrypt(DataFixture::generate(200)); + const OuterConfig encrypted2 = encryptor->encrypt(DataFixture::generate(700)); + const OuterConfig encrypted3 = encryptor->encrypt(Data(0)); EXPECT_EQ(encrypted1.encryptedInnerConfig.size(), encrypted2.encryptedInnerConfig.size()); EXPECT_EQ(encrypted1.encryptedInnerConfig.size(), encrypted3.encryptedInnerConfig.size()); diff --git a/test/cryfs/impl/filesystem/CryFsTest.cpp b/test/cryfs/impl/filesystem/CryFsTest.cpp index e44e79f0..970d576d 100644 --- a/test/cryfs/impl/filesystem/CryFsTest.cpp +++ b/test/cryfs/impl/filesystem/CryFsTest.cpp @@ -78,12 +78,12 @@ TEST_F(CryFsTest, LoadingFilesystemDoesntModifyConfigFile) { CryDevice dev(loadOrCreateConfig(), blockStore(), localStateDir, 0x12345678, false, false, failOnIntegrityViolation()); dev.setContext(fspp::Context {fspp::relatime()}); } - Data configAfterCreating = Data::LoadFromFile(config.path()).value(); + const Data configAfterCreating = Data::LoadFromFile(config.path()).value(); { CryDevice dev(loadOrCreateConfig(), blockStore(), localStateDir, 0x12345678, false, false, failOnIntegrityViolation()); dev.setContext(fspp::Context {fspp::relatime()}); } - Data configAfterLoading = Data::LoadFromFile(config.path()).value(); + const Data configAfterLoading = Data::LoadFromFile(config.path()).value(); EXPECT_EQ(configAfterCreating, configAfterLoading); } diff --git a/test/cryfs/impl/localstate/LocalStateMetadataTest.cpp b/test/cryfs/impl/localstate/LocalStateMetadataTest.cpp index c32aa700..bb382501 100644 --- a/test/cryfs/impl/localstate/LocalStateMetadataTest.cpp +++ b/test/cryfs/impl/localstate/LocalStateMetadataTest.cpp @@ -18,14 +18,14 @@ public: }; TEST_F(LocalStateMetadataTest, myClientId_ValueIsConsistent) { - LocalStateMetadata metadata1 = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); - LocalStateMetadata metadata2 = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); + const LocalStateMetadata metadata1 = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); + const LocalStateMetadata metadata2 = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); EXPECT_EQ(metadata1.myClientId(), metadata2.myClientId()); } TEST_F(LocalStateMetadataTest, myClientId_ValueIsRandomForNewClient) { - LocalStateMetadata metadata1 = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); - LocalStateMetadata metadata2 = LocalStateMetadata::loadOrGenerate(stateDir2.path(), Data(0), false); + const LocalStateMetadata metadata1 = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); + const LocalStateMetadata metadata2 = LocalStateMetadata::loadOrGenerate(stateDir2.path(), Data(0), false); EXPECT_NE(metadata1.myClientId(), metadata2.myClientId()); } @@ -35,7 +35,7 @@ TEST_F(LocalStateMetadataTest, myClientId_TakesLegacyValueIfSpecified) { file << 12345u; file.close(); - LocalStateMetadata metadata = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); + const LocalStateMetadata metadata = LocalStateMetadata::loadOrGenerate(stateDir.path(), Data(0), false); EXPECT_EQ(12345u, metadata.myClientId()); } #endif diff --git a/test/fspp/fuse/access/FuseAccessErrorTest.cpp b/test/fspp/fuse/access/FuseAccessErrorTest.cpp index e2b47de4..147eab20 100644 --- a/test/fspp/fuse/access/FuseAccessErrorTest.cpp +++ b/test/fspp/fuse/access/FuseAccessErrorTest.cpp @@ -19,6 +19,6 @@ TEST_P(FuseAccessErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, access(Eq(FILENAME), testing::_)) .Times(AtLeast(1)).WillRepeatedly(Throw(FuseErrnoException(GetParam()))); - int error = AccessFileReturnError(FILENAME, 0); + const int error = AccessFileReturnError(FILENAME, 0); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/access/testutils/FuseAccessTest.cpp b/test/fspp/fuse/access/testutils/FuseAccessTest.cpp index 5715d946..fb69f264 100644 --- a/test/fspp/fuse/access/testutils/FuseAccessTest.cpp +++ b/test/fspp/fuse/access/testutils/FuseAccessTest.cpp @@ -1,7 +1,7 @@ #include "FuseAccessTest.h" void FuseAccessTest::AccessFile(const char *filename, int mode) { - int error = AccessFileReturnError(filename, mode); + const int error = AccessFileReturnError(filename, mode); EXPECT_EQ(0, error); } @@ -9,7 +9,7 @@ int FuseAccessTest::AccessFileReturnError(const char *filename, int mode) { auto fs = TestFS(); auto realpath = fs->mountDir() / filename; - int retval = ::access(realpath.string().c_str(), mode); + const int retval = ::access(realpath.string().c_str(), mode); if (retval == 0) { return 0; } else { diff --git a/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenErrorTest.cpp b/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenErrorTest.cpp index 6310301c..8631f1f2 100644 --- a/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenErrorTest.cpp +++ b/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenErrorTest.cpp @@ -20,7 +20,7 @@ TEST_F(FuseCreateAndOpenErrorTest, ReturnNoError) { //For the syscall to succeed, we also need to give an fstat implementation. ReturnIsFileOnFstat(1); - int error = CreateAndOpenFileReturnError(FILENAME, O_RDONLY); + const int error = CreateAndOpenFileReturnError(FILENAME, O_RDONLY); EXPECT_EQ(0, error); } @@ -28,6 +28,6 @@ TEST_P(FuseCreateAndOpenErrorTest, ReturnError) { ReturnDoesntExistOnLstat(FILENAME); EXPECT_CALL(*fsimpl, createAndOpenFile(Eq(FILENAME), testing::_, testing::_, testing::_)).Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = CreateAndOpenFileReturnError(FILENAME, O_RDONLY); + const int error = CreateAndOpenFileReturnError(FILENAME, O_RDONLY); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenFileDescriptorTest.cpp b/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenFileDescriptorTest.cpp index ea931563..7ad08183 100644 --- a/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenFileDescriptorTest.cpp +++ b/test/fspp/fuse/createAndOpenFile/FuseCreateAndOpenFileDescriptorTest.cpp @@ -25,7 +25,7 @@ private: } void ReadFile(int fd) { uint8_t buf = 0; - int retval = ::read(fd, &buf, 1); + const int retval = ::read(fd, &buf, 1); EXPECT_EQ(1, retval) << "Reading file failed"; } }; diff --git a/test/fspp/fuse/fdatasync/FuseFdatasyncErrorTest.cpp b/test/fspp/fuse/fdatasync/FuseFdatasyncErrorTest.cpp index 1c685bdc..9fd02dc0 100644 --- a/test/fspp/fuse/fdatasync/FuseFdatasyncErrorTest.cpp +++ b/test/fspp/fuse/fdatasync/FuseFdatasyncErrorTest.cpp @@ -18,6 +18,6 @@ TEST_P(FuseFdatasyncErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, fdatasync(0)) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = FdatasyncFileReturnError(FILENAME); + const int error = FdatasyncFileReturnError(FILENAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/fdatasync/testutils/FuseFdatasyncTest.cpp b/test/fspp/fuse/fdatasync/testutils/FuseFdatasyncTest.cpp index 807db48f..fdc1747c 100644 --- a/test/fspp/fuse/fdatasync/testutils/FuseFdatasyncTest.cpp +++ b/test/fspp/fuse/fdatasync/testutils/FuseFdatasyncTest.cpp @@ -5,7 +5,7 @@ using cpputils::unique_ref; using cpputils::make_unique_ref; void FuseFdatasyncTest::FdatasyncFile(const char *filename) { - int error = FdatasyncFileReturnError(filename); + const int error = FdatasyncFileReturnError(filename); EXPECT_EQ(0, error); } @@ -17,7 +17,7 @@ int FuseFdatasyncTest::FdatasyncFileReturnError(const char *filename) { // This is MacOSX, which doesn't know fdatasync int retval = fcntl(fd->fd(), F_FULLFSYNC); #else - int retval = ::fdatasync(fd->fd()); + const int retval = ::fdatasync(fd->fd()); #endif if (retval != -1) { return 0; diff --git a/test/fspp/fuse/flush/FuseFlushErrorTest.cpp b/test/fspp/fuse/flush/FuseFlushErrorTest.cpp index bfa7626d..34f0b0f9 100644 --- a/test/fspp/fuse/flush/FuseFlushErrorTest.cpp +++ b/test/fspp/fuse/flush/FuseFlushErrorTest.cpp @@ -29,7 +29,7 @@ TEST_P(FuseFlushErrorTest, ReturnErrorFromFlush) { auto fs = TestFS(); auto fd = OpenFile(fs.get(), FILENAME); - int close_result = ::close(fd->fd()); + const int close_result = ::close(fd->fd()); EXPECT_EQ(GetParam(), errno); EXPECT_EQ(-1, close_result); fd->release(); // don't close it again diff --git a/test/fspp/fuse/flush/testutils/FuseFlushTest.cpp b/test/fspp/fuse/flush/testutils/FuseFlushTest.cpp index eca52cd7..29ddb8f9 100644 --- a/test/fspp/fuse/flush/testutils/FuseFlushTest.cpp +++ b/test/fspp/fuse/flush/testutils/FuseFlushTest.cpp @@ -18,6 +18,6 @@ unique_ref FuseFlushTest::OpenFile(const TempTestFS *fs, const s } void FuseFlushTest::CloseFile(int fd) { - int retval = ::close(fd); + const int retval = ::close(fd); EXPECT_EQ(0, retval); } diff --git a/test/fspp/fuse/fstat/FuseFstatErrorTest.cpp b/test/fspp/fuse/fstat/FuseFstatErrorTest.cpp index 8b75abe5..e50c03df 100644 --- a/test/fspp/fuse/fstat/FuseFstatErrorTest.cpp +++ b/test/fspp/fuse/fstat/FuseFstatErrorTest.cpp @@ -32,6 +32,6 @@ TEST_P(FuseFstatErrorTest, ReturnedErrorCodeIsCorrect) { auto fs = TestFS(); - int error = CreateFileReturnError(fs.get(), FILENAME); + const int error = CreateFileReturnError(fs.get(), FILENAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/fsync/FuseFsyncErrorTest.cpp b/test/fspp/fuse/fsync/FuseFsyncErrorTest.cpp index 36a3e17c..5fc4c7e7 100644 --- a/test/fspp/fuse/fsync/FuseFsyncErrorTest.cpp +++ b/test/fspp/fuse/fsync/FuseFsyncErrorTest.cpp @@ -18,6 +18,6 @@ TEST_P(FuseFsyncErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, fsync(0)) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = FsyncFileReturnError(FILENAME); + const int error = FsyncFileReturnError(FILENAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/fsync/testutils/FuseFsyncTest.cpp b/test/fspp/fuse/fsync/testutils/FuseFsyncTest.cpp index c74bbb65..6ac95be9 100644 --- a/test/fspp/fuse/fsync/testutils/FuseFsyncTest.cpp +++ b/test/fspp/fuse/fsync/testutils/FuseFsyncTest.cpp @@ -4,7 +4,7 @@ using cpputils::unique_ref; using cpputils::make_unique_ref; void FuseFsyncTest::FsyncFile(const char *filename) { - int error = FsyncFileReturnError(filename); + const int error = FsyncFileReturnError(filename); EXPECT_EQ(0, error); } @@ -12,7 +12,7 @@ int FuseFsyncTest::FsyncFileReturnError(const char *filename) { auto fs = TestFS(); auto fd = OpenFile(fs.get(), filename); - int retval = ::fsync(fd->fd()); + const int retval = ::fsync(fd->fd()); if (retval == 0) { return 0; } else { diff --git a/test/fspp/fuse/ftruncate/FuseFTruncateErrorTest.cpp b/test/fspp/fuse/ftruncate/FuseFTruncateErrorTest.cpp index 5832c489..402a2711 100644 --- a/test/fspp/fuse/ftruncate/FuseFTruncateErrorTest.cpp +++ b/test/fspp/fuse/ftruncate/FuseFTruncateErrorTest.cpp @@ -20,6 +20,6 @@ TEST_P(FuseFTruncateErrorTest, ReturnedErrorIsCorrect) { //Needed to make ::ftruncate system call return successfully ReturnIsFileOnFstat(0); - int error = FTruncateFileReturnError(FILENAME, fspp::num_bytes_t(0)); + const int error = FTruncateFileReturnError(FILENAME, fspp::num_bytes_t(0)); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/ftruncate/testutils/FuseFTruncateTest.cpp b/test/fspp/fuse/ftruncate/testutils/FuseFTruncateTest.cpp index caa3a3dd..741570ce 100644 --- a/test/fspp/fuse/ftruncate/testutils/FuseFTruncateTest.cpp +++ b/test/fspp/fuse/ftruncate/testutils/FuseFTruncateTest.cpp @@ -4,7 +4,7 @@ using cpputils::unique_ref; using cpputils::make_unique_ref; void FuseFTruncateTest::FTruncateFile(const char *filename, fspp::num_bytes_t size) { - int error = FTruncateFileReturnError(filename, size); + const int error = FTruncateFileReturnError(filename, size); EXPECT_EQ(0, error); } @@ -12,7 +12,7 @@ int FuseFTruncateTest::FTruncateFileReturnError(const char *filename, fspp::num_ auto fs = TestFS(); auto fd = OpenFile(fs.get(), filename); - int retval = ::ftruncate(fd->fd(), size.value()); + const int retval = ::ftruncate(fd->fd(), size.value()); if (0 == retval) { return 0; } else { diff --git a/test/fspp/fuse/lstat/FuseLstatErrorTest.cpp b/test/fspp/fuse/lstat/FuseLstatErrorTest.cpp index f6dd299b..92b57e2d 100644 --- a/test/fspp/fuse/lstat/FuseLstatErrorTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatErrorTest.cpp @@ -18,12 +18,12 @@ INSTANTIATE_TEST_SUITE_P(LstatErrorCodes, FuseLstatErrorTest, Values(EACCES, EBA TEST_F(FuseLstatErrorTest, ReturnNoError) { EXPECT_CALL(*fsimpl, lstat(Eq(FILENAME), testing::_)).Times(AtLeast(1)).WillRepeatedly(ReturnIsFile); errno = 0; - int error = LstatPathReturnError(FILENAME); + const int error = LstatPathReturnError(FILENAME); EXPECT_EQ(0, error); } TEST_P(FuseLstatErrorTest, ReturnError) { EXPECT_CALL(*fsimpl, lstat(Eq(FILENAME), testing::_)).Times(AtLeast(1)).WillRepeatedly(Throw(FuseErrnoException(GetParam()))); - int error = LstatPathReturnError(FILENAME); + const int error = LstatPathReturnError(FILENAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnAtimeTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnAtimeTest.cpp index b5f6f5ce..7c051f3f 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnAtimeTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnAtimeTest.cpp @@ -19,13 +19,13 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnATimeTest, FuseLstatReturnATimeTest, Val )); TEST_P(FuseLstatReturnATimeTest, ReturnedFileAtimeIsCorrect) { - fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_atim.tv_sec); EXPECT_EQ(0, result.st_atim.tv_nsec); } TEST_P(FuseLstatReturnATimeTest, ReturnedDirAtimeIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_atim.tv_sec); EXPECT_EQ(0, result.st_atim.tv_nsec); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnCtimeTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnCtimeTest.cpp index 051c1487..8f7dc18b 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnCtimeTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnCtimeTest.cpp @@ -19,13 +19,13 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnCtimeTest, FuseLstatReturnCtimeTest, Val )); TEST_P(FuseLstatReturnCtimeTest, ReturnedFileCtimeIsCorrect) { - fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_ctim.tv_sec); EXPECT_EQ(0, result.st_ctim.tv_nsec); } TEST_P(FuseLstatReturnCtimeTest, ReturnedDirCtimeIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_ctim.tv_sec); EXPECT_EQ(0, result.st_ctim.tv_nsec); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnGidTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnGidTest.cpp index b7721778..11800c0b 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnGidTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnGidTest.cpp @@ -15,11 +15,11 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnGidTest, FuseLstatReturnGidTest, Values( )); TEST_P(FuseLstatReturnGidTest, ReturnedFileGidIsCorrect) { - fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_gid); } TEST_P(FuseLstatReturnGidTest, ReturnedDirGidIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_gid); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnModeTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnModeTest.cpp index 87d4d28f..331dde74 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnModeTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnModeTest.cpp @@ -19,6 +19,6 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnModeTest, FuseLstatReturnModeTest, Value )); TEST_P(FuseLstatReturnModeTest, ReturnedModeIsCorrect) { - fspp::fuse::STAT result = CallLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_mode); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnMtimeTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnMtimeTest.cpp index a01f3180..95f38ca1 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnMtimeTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnMtimeTest.cpp @@ -19,13 +19,13 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnMtimeTest, FuseLstatReturnMtimeTest, Val )); TEST_P(FuseLstatReturnMtimeTest, ReturnedFileMtimeIsCorrect) { - fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_mtim.tv_sec); EXPECT_EQ(0, result.st_mtim.tv_nsec); } TEST_P(FuseLstatReturnMtimeTest, ReturnedDirMtimeIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_mtim.tv_sec); EXPECT_EQ(0, result.st_mtim.tv_nsec); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnNlinkTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnNlinkTest.cpp index cb0e7fc9..6e822075 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnNlinkTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnNlinkTest.cpp @@ -17,12 +17,12 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnNlinkTest, FuseLstatReturnNlinkTest, Val )); TEST_P(FuseLstatReturnNlinkTest, ReturnedFileNlinkIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_nlink); } TEST_P(FuseLstatReturnNlinkTest, ReturnedDirNlinkIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_nlink); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnSizeTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnSizeTest.cpp index 40dd7f0d..5a0e9d98 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnSizeTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnSizeTest.cpp @@ -17,11 +17,11 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnSizeTest, FuseLstatReturnSizeTest, Value )); TEST_P(FuseLstatReturnSizeTest, ReturnedFileSizeIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), fspp::num_bytes_t(result.st_size)); } TEST_P(FuseLstatReturnSizeTest, ReturnedDirSizeIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), fspp::num_bytes_t(result.st_size)); } diff --git a/test/fspp/fuse/lstat/FuseLstatReturnUidTest.cpp b/test/fspp/fuse/lstat/FuseLstatReturnUidTest.cpp index 25ca37bb..d3ae38d3 100644 --- a/test/fspp/fuse/lstat/FuseLstatReturnUidTest.cpp +++ b/test/fspp/fuse/lstat/FuseLstatReturnUidTest.cpp @@ -15,11 +15,11 @@ INSTANTIATE_TEST_SUITE_P(FuseLstatReturnUidTest, FuseLstatReturnUidTest, Values( )); TEST_P(FuseLstatReturnUidTest, ReturnedFileUidIsCorrect) { - fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallFileLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_uid); } TEST_P(FuseLstatReturnUidTest, ReturnedDirUidIsCorrect) { - fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); + const fspp::fuse::STAT result = CallDirLstatWithValue(GetParam()); EXPECT_EQ(GetParam(), result.st_uid); } diff --git a/test/fspp/fuse/lstat/testutils/FuseLstatTest.cpp b/test/fspp/fuse/lstat/testutils/FuseLstatTest.cpp index d0246eba..8282eeb3 100644 --- a/test/fspp/fuse/lstat/testutils/FuseLstatTest.cpp +++ b/test/fspp/fuse/lstat/testutils/FuseLstatTest.cpp @@ -15,7 +15,7 @@ int FuseLstatTest::LstatPathReturnError(const std::string &path) { } void FuseLstatTest::LstatPath(const std::string &path, fspp::fuse::STAT *result) { - int error = LstatPathReturnError(path, result); + const int error = LstatPathReturnError(path, result); EXPECT_EQ(0, error) << "lstat syscall failed. errno: " << error; } @@ -23,7 +23,7 @@ int FuseLstatTest::LstatPathReturnError(const std::string &path, fspp::fuse::STA auto fs = TestFS(); auto realpath = fs->mountDir() / path; - int retval = ::lstat(realpath.string().c_str(), result); + const int retval = ::lstat(realpath.string().c_str(), result); if (retval == 0) { return 0; } else { diff --git a/test/fspp/fuse/mkdir/FuseMkdirErrorTest.cpp b/test/fspp/fuse/mkdir/FuseMkdirErrorTest.cpp index e4cb487c..f5cb247c 100644 --- a/test/fspp/fuse/mkdir/FuseMkdirErrorTest.cpp +++ b/test/fspp/fuse/mkdir/FuseMkdirErrorTest.cpp @@ -18,7 +18,7 @@ TEST_F(FuseMkdirErrorTest, NoError) { EXPECT_CALL(*fsimpl, mkdir(Eq(DIRNAME), testing::_, testing::_, testing::_)) .Times(1).WillOnce(FromNowOnReturnIsDirOnLstat()); - int error = MkdirReturnError(DIRNAME, 0); + const int error = MkdirReturnError(DIRNAME, 0); EXPECT_EQ(0, error); } @@ -27,6 +27,6 @@ TEST_P(FuseMkdirErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, mkdir(Eq(DIRNAME), testing::_, testing::_, testing::_)) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = MkdirReturnError(DIRNAME, 0); + const int error = MkdirReturnError(DIRNAME, 0); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/mkdir/testutils/FuseMkdirTest.cpp b/test/fspp/fuse/mkdir/testutils/FuseMkdirTest.cpp index 17c18457..a3b9656d 100644 --- a/test/fspp/fuse/mkdir/testutils/FuseMkdirTest.cpp +++ b/test/fspp/fuse/mkdir/testutils/FuseMkdirTest.cpp @@ -4,7 +4,7 @@ using ::testing::Action; using ::testing::Invoke; void FuseMkdirTest::Mkdir(const char *dirname, mode_t mode) { - int error = MkdirReturnError(dirname, mode); + const int error = MkdirReturnError(dirname, mode); EXPECT_EQ(0, error); } @@ -12,7 +12,7 @@ int FuseMkdirTest::MkdirReturnError(const char *dirname, mode_t mode) { auto fs = TestFS(); auto realpath = fs->mountDir() / dirname; - int retval = ::mkdir(realpath.string().c_str(), mode); + const int retval = ::mkdir(realpath.string().c_str(), mode); if (retval == 0) { return 0; } else { diff --git a/test/fspp/fuse/openFile/FuseOpenErrorTest.cpp b/test/fspp/fuse/openFile/FuseOpenErrorTest.cpp index ac08f060..1213e8b9 100644 --- a/test/fspp/fuse/openFile/FuseOpenErrorTest.cpp +++ b/test/fspp/fuse/openFile/FuseOpenErrorTest.cpp @@ -18,13 +18,13 @@ TEST_F(FuseOpenErrorTest, ReturnNoError) { ReturnIsFileOnLstat(FILENAME); EXPECT_CALL(*fsimpl, openFile(Eq(FILENAME), testing::_)).Times(1).WillOnce(Return(1)); errno = 0; - int error = OpenFileReturnError(FILENAME, O_RDONLY); + const int error = OpenFileReturnError(FILENAME, O_RDONLY); EXPECT_EQ(0, error); } TEST_P(FuseOpenErrorTest, ReturnError) { ReturnIsFileOnLstat(FILENAME); EXPECT_CALL(*fsimpl, openFile(Eq(FILENAME), testing::_)).Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = OpenFileReturnError(FILENAME, O_RDONLY); + const int error = OpenFileReturnError(FILENAME, O_RDONLY); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/openFile/FuseOpenFileDescriptorTest.cpp b/test/fspp/fuse/openFile/FuseOpenFileDescriptorTest.cpp index f4ddfa92..4871e46c 100644 --- a/test/fspp/fuse/openFile/FuseOpenFileDescriptorTest.cpp +++ b/test/fspp/fuse/openFile/FuseOpenFileDescriptorTest.cpp @@ -25,7 +25,7 @@ private: } void ReadFile(int fd) { uint8_t buf = 0; - int retval = ::read(fd, &buf, 1); + const ssize_t retval = ::read(fd, &buf, 1); EXPECT_EQ(1, retval) << "Reading file failed"; } }; diff --git a/test/fspp/fuse/read/FuseReadErrorTest.cpp b/test/fspp/fuse/read/FuseReadErrorTest.cpp index 3772a1c1..9b512ace 100644 --- a/test/fspp/fuse/read/FuseReadErrorTest.cpp +++ b/test/fspp/fuse/read/FuseReadErrorTest.cpp @@ -1,3 +1,5 @@ +#include + #include "testutils/FuseReadTest.h" #include "fspp/fs_interface/FuseErrnoException.h" diff --git a/test/fspp/fuse/readDir/FuseReadDirErrorTest.cpp b/test/fspp/fuse/readDir/FuseReadDirErrorTest.cpp index ffb96f21..1e5625e0 100644 --- a/test/fspp/fuse/readDir/FuseReadDirErrorTest.cpp +++ b/test/fspp/fuse/readDir/FuseReadDirErrorTest.cpp @@ -22,7 +22,7 @@ TEST_F(FuseReadDirErrorTest, NoError) { EXPECT_CALL(*fsimpl, readDir(Eq(DIRNAME))) .Times(1).WillOnce(ReturnDirEntries({})); - int error = ReadDirReturnError(DIRNAME); + const int error = ReadDirReturnError(DIRNAME); EXPECT_EQ(0, error); } @@ -31,6 +31,6 @@ TEST_P(FuseReadDirErrorTest, ReturnedErrorCodeIsCorrect) { EXPECT_CALL(*fsimpl, readDir(Eq(DIRNAME))) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = ReadDirReturnError(DIRNAME); + const int error = ReadDirReturnError(DIRNAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/readDir/testutils/FuseReadDirTest.cpp b/test/fspp/fuse/readDir/testutils/FuseReadDirTest.cpp index 3d15eff2..8a4ab156 100644 --- a/test/fspp/fuse/readDir/testutils/FuseReadDirTest.cpp +++ b/test/fspp/fuse/readDir/testutils/FuseReadDirTest.cpp @@ -29,7 +29,7 @@ int FuseReadDirTest::ReadDirReturnError(const char *dirname) { } auto result = make_unique_ref>(); - int error = readDirEntriesAllowError(dir, result.get()); + const int error = readDirEntriesAllowError(dir, result.get()); closeDir(dir); return error; } @@ -46,19 +46,19 @@ DIR *FuseReadDirTest::openDirAllowError(TempTestFS *fs, const char *dirname) { } void FuseReadDirTest::readDirEntries(DIR *dir, vector *result) { - int error = readDirEntriesAllowError(dir, result); + const int error = readDirEntriesAllowError(dir, result); EXPECT_EQ(0, error); } int FuseReadDirTest::readDirEntriesAllowError(DIR *dir, vector *result) { struct dirent *entry = nullptr; - int error = readNextDirEntryAllowError(dir, &entry); + const int error = readNextDirEntryAllowError(dir, &entry); if (error != 0) { return error; } while(entry != nullptr) { result->push_back(entry->d_name); - int error = readNextDirEntryAllowError(dir, &entry); + const int error = readNextDirEntryAllowError(dir, &entry); if (error != 0) { return error; } @@ -73,7 +73,7 @@ int FuseReadDirTest::readNextDirEntryAllowError(DIR *dir, struct dirent **result } void FuseReadDirTest::closeDir(DIR *dir) { - int retval = ::closedir(dir); + const int retval = ::closedir(dir); EXPECT_EQ(0, retval) << "Closing dir failed"; } diff --git a/test/fspp/fuse/rename/FuseRenameErrorTest.cpp b/test/fspp/fuse/rename/FuseRenameErrorTest.cpp index d4c9df85..9ad29251 100644 --- a/test/fspp/fuse/rename/FuseRenameErrorTest.cpp +++ b/test/fspp/fuse/rename/FuseRenameErrorTest.cpp @@ -18,6 +18,6 @@ TEST_P(FuseRenameErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, rename(Eq(FILENAME1), Eq(FILENAME2))) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = RenameReturnError(FILENAME1, FILENAME2); + const int error = RenameReturnError(FILENAME1, FILENAME2); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/rename/testutils/FuseRenameTest.cpp b/test/fspp/fuse/rename/testutils/FuseRenameTest.cpp index e74945b4..cec9fd8b 100644 --- a/test/fspp/fuse/rename/testutils/FuseRenameTest.cpp +++ b/test/fspp/fuse/rename/testutils/FuseRenameTest.cpp @@ -2,7 +2,7 @@ void FuseRenameTest::Rename(const char *from, const char *to) { - int error = RenameReturnError(from, to); + const int error = RenameReturnError(from, to); EXPECT_EQ(0, error); } @@ -11,7 +11,7 @@ int FuseRenameTest::RenameReturnError(const char *from, const char *to) { auto realfrom = fs->mountDir() / from; auto realto = fs->mountDir() / to; - int retval = ::rename(realfrom.string().c_str(), realto.string().c_str()); + const int retval = ::rename(realfrom.string().c_str(), realto.string().c_str()); if (0 == retval) { return 0; } else { diff --git a/test/fspp/fuse/rmdir/FuseRmdirErrorTest.cpp b/test/fspp/fuse/rmdir/FuseRmdirErrorTest.cpp index a19d489c..d98106e6 100644 --- a/test/fspp/fuse/rmdir/FuseRmdirErrorTest.cpp +++ b/test/fspp/fuse/rmdir/FuseRmdirErrorTest.cpp @@ -17,6 +17,6 @@ TEST_P(FuseRmdirErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, rmdir(Eq(DIRNAME))) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = RmdirReturnError(DIRNAME); + const int error = RmdirReturnError(DIRNAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/rmdir/testutils/FuseRmdirTest.cpp b/test/fspp/fuse/rmdir/testutils/FuseRmdirTest.cpp index 3b0e1a2a..329518d8 100644 --- a/test/fspp/fuse/rmdir/testutils/FuseRmdirTest.cpp +++ b/test/fspp/fuse/rmdir/testutils/FuseRmdirTest.cpp @@ -4,7 +4,7 @@ using ::testing::Action; using ::testing::Invoke; void FuseRmdirTest::Rmdir(const char *dirname) { - int error = RmdirReturnError(dirname); + const int error = RmdirReturnError(dirname); EXPECT_EQ(0, error); } @@ -12,7 +12,7 @@ int FuseRmdirTest::RmdirReturnError(const char *dirname) { auto fs = TestFS(); auto realpath = fs->mountDir() / dirname; - int retval = ::rmdir(realpath.string().c_str()); + const int retval = ::rmdir(realpath.string().c_str()); if (retval == 0) { return 0; } else { diff --git a/test/fspp/fuse/statfs/FuseStatfsErrorTest.cpp b/test/fspp/fuse/statfs/FuseStatfsErrorTest.cpp index 0ef53749..775a7f0a 100644 --- a/test/fspp/fuse/statfs/FuseStatfsErrorTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsErrorTest.cpp @@ -17,13 +17,13 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsErrorTest, FuseStatfsErrorTest, Values(EACCES TEST_F(FuseStatfsErrorTest, ReturnNoError) { ReturnIsFileOnLstat(FILENAME); EXPECT_CALL(*fsimpl, statfs(testing::_)).Times(1).WillOnce(Return()); - int error = StatfsReturnError(FILENAME); + const int error = StatfsReturnError(FILENAME); EXPECT_EQ(0, error); } TEST_P(FuseStatfsErrorTest, ReturnError) { ReturnIsFileOnLstat(FILENAME); EXPECT_CALL(*fsimpl, statfs(testing::_)).Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = StatfsReturnError(FILENAME); + const int error = StatfsReturnError(FILENAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/statfs/FuseStatfsReturnBavailTest.cpp b/test/fspp/fuse/statfs/FuseStatfsReturnBavailTest.cpp index 733fee72..0cf922d6 100644 --- a/test/fspp/fuse/statfs/FuseStatfsReturnBavailTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsReturnBavailTest.cpp @@ -18,6 +18,6 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsReturnBavailTest, FuseStatfsReturnBavailTest, )); TEST_P(FuseStatfsReturnBavailTest, ReturnedBavailIsCorrect) { - struct ::statvfs result = CallStatfsWithValue(GetParam()); + const struct ::statvfs result = CallStatfsWithValue(GetParam()); EXPECT_EQ(GetParam(), result.f_bavail); } diff --git a/test/fspp/fuse/statfs/FuseStatfsReturnBfreeTest.cpp b/test/fspp/fuse/statfs/FuseStatfsReturnBfreeTest.cpp index 9e3ef5c1..82186926 100644 --- a/test/fspp/fuse/statfs/FuseStatfsReturnBfreeTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsReturnBfreeTest.cpp @@ -18,6 +18,6 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsReturnBfreeTest, FuseStatfsReturnBfreeTest, V )); TEST_P(FuseStatfsReturnBfreeTest, ReturnedBfreeIsCorrect) { - struct ::statvfs result = CallStatfsWithValue(GetParam()); + const struct ::statvfs result = CallStatfsWithValue(GetParam()); EXPECT_EQ(GetParam(), result.f_bfree); } diff --git a/test/fspp/fuse/statfs/FuseStatfsReturnBlocksTest.cpp b/test/fspp/fuse/statfs/FuseStatfsReturnBlocksTest.cpp index f77a80ee..e346bade 100644 --- a/test/fspp/fuse/statfs/FuseStatfsReturnBlocksTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsReturnBlocksTest.cpp @@ -18,6 +18,6 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsReturnBlocksTest, FuseStatfsReturnBlocksTest, )); TEST_P(FuseStatfsReturnBlocksTest, ReturnedBlocksIsCorrect) { - struct ::statvfs result = CallStatfsWithValue(GetParam()); + const struct ::statvfs result = CallStatfsWithValue(GetParam()); EXPECT_EQ(GetParam(), result.f_blocks); } diff --git a/test/fspp/fuse/statfs/FuseStatfsReturnBsizeTest.cpp b/test/fspp/fuse/statfs/FuseStatfsReturnBsizeTest.cpp index bbb84161..dc02971e 100644 --- a/test/fspp/fuse/statfs/FuseStatfsReturnBsizeTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsReturnBsizeTest.cpp @@ -18,6 +18,6 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsReturnBsizeTest, FuseStatfsReturnBsizeTest, V )); TEST_P(FuseStatfsReturnBsizeTest, ReturnedBsizeIsCorrect) { - struct ::statvfs result = CallStatfsWithValue(GetParam()); + const struct ::statvfs result = CallStatfsWithValue(GetParam()); EXPECT_EQ(GetParam(), result.f_bsize); } diff --git a/test/fspp/fuse/statfs/FuseStatfsReturnFfreeTest.cpp b/test/fspp/fuse/statfs/FuseStatfsReturnFfreeTest.cpp index 9cf015a2..a36cbc56 100644 --- a/test/fspp/fuse/statfs/FuseStatfsReturnFfreeTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsReturnFfreeTest.cpp @@ -18,6 +18,6 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsReturnFfreeTest, FuseStatfsReturnFfreeTest, V )); TEST_P(FuseStatfsReturnFfreeTest, ReturnedFfreeIsCorrect) { - struct ::statvfs result = CallStatfsWithValue(GetParam()); + const struct ::statvfs result = CallStatfsWithValue(GetParam()); EXPECT_EQ(GetParam(), result.f_ffree); } diff --git a/test/fspp/fuse/statfs/FuseStatfsReturnFilesTest.cpp b/test/fspp/fuse/statfs/FuseStatfsReturnFilesTest.cpp index acef1dff..1c04b53b 100644 --- a/test/fspp/fuse/statfs/FuseStatfsReturnFilesTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsReturnFilesTest.cpp @@ -18,6 +18,6 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsReturnFilesTest, FuseStatfsReturnFilesTest, V )); TEST_P(FuseStatfsReturnFilesTest, ReturnedFilesIsCorrect) { - struct ::statvfs result = CallStatfsWithValue(GetParam()); + const struct ::statvfs result = CallStatfsWithValue(GetParam()); EXPECT_EQ(GetParam(), result.f_files); } diff --git a/test/fspp/fuse/statfs/FuseStatfsReturnNamemaxTest.cpp b/test/fspp/fuse/statfs/FuseStatfsReturnNamemaxTest.cpp index ce180c3a..65879416 100644 --- a/test/fspp/fuse/statfs/FuseStatfsReturnNamemaxTest.cpp +++ b/test/fspp/fuse/statfs/FuseStatfsReturnNamemaxTest.cpp @@ -18,6 +18,6 @@ INSTANTIATE_TEST_SUITE_P(FuseStatfsReturnNamemaxTest, FuseStatfsReturnNamemaxTes )); TEST_P(FuseStatfsReturnNamemaxTest, ReturnedNamemaxIsCorrect) { - struct ::statvfs result = CallStatfsWithValue(GetParam()); + const struct ::statvfs result = CallStatfsWithValue(GetParam()); EXPECT_EQ(GetParam(), result.f_namemax); } diff --git a/test/fspp/fuse/statfs/testutils/FuseStatfsTest.cpp b/test/fspp/fuse/statfs/testutils/FuseStatfsTest.cpp index 651c85d0..ae48f11c 100644 --- a/test/fspp/fuse/statfs/testutils/FuseStatfsTest.cpp +++ b/test/fspp/fuse/statfs/testutils/FuseStatfsTest.cpp @@ -14,7 +14,7 @@ int FuseStatfsTest::StatfsReturnError(const std::string &path) { } void FuseStatfsTest::Statfs(const std::string &path, struct ::statvfs *result) { - int error = StatfsReturnError(path, result); + const int error = StatfsReturnError(path, result); EXPECT_EQ(0, error) << "lstat syscall failed. errno: " << errno; } @@ -22,7 +22,7 @@ int FuseStatfsTest::StatfsReturnError(const std::string &path, struct ::statvfs auto fs = TestFS(); auto realpath = fs->mountDir() / path; - int retval = ::statvfs(realpath.string().c_str(), result); + const int retval = ::statvfs(realpath.string().c_str(), result); if (retval == 0) { return 0; } else { diff --git a/test/fspp/fuse/truncate/FuseTruncateErrorTest.cpp b/test/fspp/fuse/truncate/FuseTruncateErrorTest.cpp index 65048974..870e7bc3 100644 --- a/test/fspp/fuse/truncate/FuseTruncateErrorTest.cpp +++ b/test/fspp/fuse/truncate/FuseTruncateErrorTest.cpp @@ -17,6 +17,6 @@ TEST_P(FuseTruncateErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, truncate(Eq(FILENAME), testing::_)) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = TruncateFileReturnError(FILENAME, fspp::num_bytes_t(0)); + const int error = TruncateFileReturnError(FILENAME, fspp::num_bytes_t(0)); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/truncate/testutils/FuseTruncateTest.cpp b/test/fspp/fuse/truncate/testutils/FuseTruncateTest.cpp index a461547b..e419e6da 100644 --- a/test/fspp/fuse/truncate/testutils/FuseTruncateTest.cpp +++ b/test/fspp/fuse/truncate/testutils/FuseTruncateTest.cpp @@ -1,7 +1,7 @@ #include "FuseTruncateTest.h" void FuseTruncateTest::TruncateFile(const char *filename, fspp::num_bytes_t size) { - int error = TruncateFileReturnError(filename, size); + const int error = TruncateFileReturnError(filename, size); EXPECT_EQ(0, error); } @@ -9,7 +9,7 @@ int FuseTruncateTest::TruncateFileReturnError(const char *filename, fspp::num_by auto fs = TestFS(); auto realpath = fs->mountDir() / filename; - int retval = ::truncate(realpath.string().c_str(), size.value()); + const int retval = ::truncate(realpath.string().c_str(), size.value()); if (retval == 0) { return 0; } else { diff --git a/test/fspp/fuse/unlink/FuseUnlinkErrorTest.cpp b/test/fspp/fuse/unlink/FuseUnlinkErrorTest.cpp index b04dd675..e3eacef3 100644 --- a/test/fspp/fuse/unlink/FuseUnlinkErrorTest.cpp +++ b/test/fspp/fuse/unlink/FuseUnlinkErrorTest.cpp @@ -17,6 +17,6 @@ TEST_P(FuseUnlinkErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, unlink(Eq(FILENAME))) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = UnlinkReturnError(FILENAME); + const int error = UnlinkReturnError(FILENAME); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/unlink/testutils/FuseUnlinkTest.cpp b/test/fspp/fuse/unlink/testutils/FuseUnlinkTest.cpp index 63dedf67..fb9255d7 100644 --- a/test/fspp/fuse/unlink/testutils/FuseUnlinkTest.cpp +++ b/test/fspp/fuse/unlink/testutils/FuseUnlinkTest.cpp @@ -4,7 +4,7 @@ using ::testing::Action; using ::testing::Invoke; void FuseUnlinkTest::Unlink(const char *filename) { - int error = UnlinkReturnError(filename); + const int error = UnlinkReturnError(filename); EXPECT_EQ(0, error); } @@ -12,7 +12,7 @@ int FuseUnlinkTest::UnlinkReturnError(const char *filename) { auto fs = TestFS(); auto realpath = fs->mountDir() / filename; - int retval = ::unlink(realpath.string().c_str()); + const int retval = ::unlink(realpath.string().c_str()); if (0 == retval) { return 0; } else { diff --git a/test/fspp/fuse/utimens/FuseUtimensErrorTest.cpp b/test/fspp/fuse/utimens/FuseUtimensErrorTest.cpp index ad6732fb..2bfa2174 100644 --- a/test/fspp/fuse/utimens/FuseUtimensErrorTest.cpp +++ b/test/fspp/fuse/utimens/FuseUtimensErrorTest.cpp @@ -17,6 +17,6 @@ TEST_P(FuseUtimensErrorTest, ReturnedErrorIsCorrect) { EXPECT_CALL(*fsimpl, utimens(Eq(FILENAME), testing::_, testing::_)) .Times(1).WillOnce(Throw(FuseErrnoException(GetParam()))); - int error = UtimensReturnError(FILENAME, TIMEVALUE, TIMEVALUE); + const int error = UtimensReturnError(FILENAME, TIMEVALUE, TIMEVALUE); EXPECT_EQ(GetParam(), error); } diff --git a/test/fspp/fuse/utimens/testutils/FuseUtimensTest.cpp b/test/fspp/fuse/utimens/testutils/FuseUtimensTest.cpp index 4ae8368b..b8934a7e 100644 --- a/test/fspp/fuse/utimens/testutils/FuseUtimensTest.cpp +++ b/test/fspp/fuse/utimens/testutils/FuseUtimensTest.cpp @@ -2,7 +2,7 @@ #include void FuseUtimensTest::Utimens(const char *filename, timespec lastAccessTime, timespec lastModificationTime) { - int error = UtimensReturnError(filename, lastAccessTime, lastModificationTime); + const int error = UtimensReturnError(filename, lastAccessTime, lastModificationTime); EXPECT_EQ(0, error); } diff --git a/test/fspp/fuse/write/FuseWriteErrorTest.cpp b/test/fspp/fuse/write/FuseWriteErrorTest.cpp index 932f384e..f547246b 100644 --- a/test/fspp/fuse/write/FuseWriteErrorTest.cpp +++ b/test/fspp/fuse/write/FuseWriteErrorTest.cpp @@ -1,3 +1,5 @@ +#include + #include "testutils/FuseWriteTest.h" #include "fspp/fs_interface/FuseErrnoException.h" diff --git a/test/fspp/impl/FuseOpenFileListTest.cpp b/test/fspp/impl/FuseOpenFileListTest.cpp index e59fe558..228b5fa5 100644 --- a/test/fspp/impl/FuseOpenFileListTest.cpp +++ b/test/fspp/impl/FuseOpenFileListTest.cpp @@ -15,7 +15,7 @@ public: int fileid, flags; bool destructed; - ~MockOpenFile() {destructed = true;} + ~MockOpenFile() override {destructed = true;} MOCK_METHOD(OpenFile::stat_info, stat, (), (const, override)); MOCK_METHOD(void, truncate, (fspp::num_bytes_t), (const, override)); @@ -62,28 +62,28 @@ TEST_F(FuseOpenFileListTest, EmptyList2) { } TEST_F(FuseOpenFileListTest, InvalidId) { - int valid_id = open(); - int invalid_id = valid_id + 1; + const int valid_id = open(); + const int invalid_id = valid_id + 1; ASSERT_THROW(list.load(invalid_id, [](OpenFile*) {}), fspp::fuse::FuseErrnoException); } TEST_F(FuseOpenFileListTest, Open1AndGet) { - int id = open(FILEID1, FLAGS1); + const int id = open(FILEID1, FLAGS1); check(id, FILEID1, FLAGS1); } TEST_F(FuseOpenFileListTest, Open2AndGet) { - int id1 = open(FILEID1, FLAGS1); - int id2 = open(FILEID2, FLAGS2); + const int id1 = open(FILEID1, FLAGS1); + const int id2 = open(FILEID2, FLAGS2); check(id1, FILEID1, FLAGS1); check(id2, FILEID2, FLAGS2); } TEST_F(FuseOpenFileListTest, Open3AndGet) { - int id1 = open(FILEID1, FLAGS1); - int id2 = open(FILEID2, FLAGS2); - int id3 = open(FILEID3, FLAGS3); + const int id1 = open(FILEID1, FLAGS1); + const int id2 = open(FILEID2, FLAGS2); + const int id3 = open(FILEID3, FLAGS3); check(id1, FILEID1, FLAGS1); check(id3, FILEID3, FLAGS3); @@ -102,7 +102,7 @@ TEST_F(FuseOpenFileListTest, Open3AndGet) { }*/ TEST_F(FuseOpenFileListTest, GetClosedItemOnEmptyList) { - int id = open(); + const int id = open(); ASSERT_NO_THROW(list.load(id, [](OpenFile*) {})); list.close(id); @@ -110,7 +110,7 @@ TEST_F(FuseOpenFileListTest, GetClosedItemOnEmptyList) { } TEST_F(FuseOpenFileListTest, GetClosedItemOnNonEmptyList) { - int id = open(); + const int id = open(); open(); ASSERT_NO_THROW(list.load(id, [](OpenFile*) {})); @@ -127,7 +127,7 @@ TEST_F(FuseOpenFileListTest, CloseOnEmptyList2) { } TEST_F(FuseOpenFileListTest, RemoveInvalidId) { - int valid_id = open(); - int invalid_id = valid_id + 1; + const int valid_id = open(); + const int invalid_id = valid_id + 1; ASSERT_THROW(list.close(invalid_id), std::out_of_range); } diff --git a/test/fspp/impl/IdListTest.cpp b/test/fspp/impl/IdListTest.cpp index dc6b289d..3f2d2453 100644 --- a/test/fspp/impl/IdListTest.cpp +++ b/test/fspp/impl/IdListTest.cpp @@ -46,19 +46,19 @@ TEST_F(IdListTest, EmptyList2) { } TEST_F(IdListTest, InvalidId) { - int valid_id = add(); - int invalid_id = valid_id + 1; + const int valid_id = add(); + const int invalid_id = valid_id + 1; ASSERT_THROW(list.get(invalid_id), std::out_of_range); } TEST_F(IdListTest, GetRemovedItemOnEmptyList) { - int id = add(); + const int id = add(); list.remove(id); ASSERT_THROW(list.get(id), std::out_of_range); } TEST_F(IdListTest, GetRemovedItemOnNonEmptyList) { - int id = add(); + const int id = add(); add(); list.remove(id); ASSERT_THROW(list.get(id), std::out_of_range); @@ -73,36 +73,36 @@ TEST_F(IdListTest, RemoveOnEmptyList2) { } TEST_F(IdListTest, RemoveInvalidId) { - int valid_id = add(); - int invalid_id = valid_id + 1; + const int valid_id = add(); + const int invalid_id = valid_id + 1; ASSERT_THROW(list.remove(invalid_id), std::out_of_range); } TEST_F(IdListTest, Add1AndGet) { - int id = add(OBJ1); + const int id = add(OBJ1); check(id, OBJ1); } TEST_F(IdListTest, Add2AndGet) { - int id1 = add(OBJ1); - int id2 = add(OBJ2); + const int id1 = add(OBJ1); + const int id2 = add(OBJ2); check(id1, OBJ1); check(id2, OBJ2); } TEST_F(IdListTest, Add3AndGet) { - int id1 = add(OBJ1); - int id2 = add(OBJ2); - int id3 = add(OBJ3); + const int id1 = add(OBJ1); + const int id2 = add(OBJ2); + const int id3 = add(OBJ3); check(id1, OBJ1); check(id3, OBJ3); check(id2, OBJ2); } TEST_F(IdListTest, Add3AndConstGet) { - int id1 = add(OBJ1); - int id2 = add(OBJ2); - int id3 = add(OBJ3); + const int id1 = add(OBJ1); + const int id2 = add(OBJ2); + const int id3 = add(OBJ3); checkConst(id1, OBJ1); checkConst(id3, OBJ3); checkConst(id2, OBJ2); diff --git a/test/fspp/testutils/FuseTest.h b/test/fspp/testutils/FuseTest.h index 8430182f..08ca036a 100644 --- a/test/fspp/testutils/FuseTest.h +++ b/test/fspp/testutils/FuseTest.h @@ -18,7 +18,7 @@ class MockFilesystem: public fspp::fuse::Filesystem { public: MockFilesystem(); - virtual ~MockFilesystem(); + ~MockFilesystem() override; MOCK_METHOD(void, setContext, (fspp::Context&&), (override)); MOCK_METHOD(int, openFile, (const boost::filesystem::path&, int), (override)); diff --git a/test/fspp/testutils/FuseThread.cpp b/test/fspp/testutils/FuseThread.cpp index 32f022df..cfddb35d 100644 --- a/test/fspp/testutils/FuseThread.cpp +++ b/test/fspp/testutils/FuseThread.cpp @@ -30,7 +30,7 @@ void FuseThread::start(const bf::path &mountDir, const vector &fuseOptio void FuseThread::stop() { _fuse->stop(); - bool thread_stopped = _child.try_join_for(seconds(10)); + const bool thread_stopped = _child.try_join_for(seconds(10)); ASSERT(thread_stopped, "FuseThread could not be stopped"); //Wait until it is properly shutdown (busy waiting is simple and doesn't hurt much here) while (_fuse->running()) {} diff --git a/test/gitversion/ParserTest.cpp b/test/gitversion/ParserTest.cpp index 11a3875a..537739fb 100644 --- a/test/gitversion/ParserTest.cpp +++ b/test/gitversion/ParserTest.cpp @@ -4,7 +4,7 @@ using namespace gitversion; TEST(ParserTest, TestUnknownVersion) { - VersionInfo info = Parser::parse("0+unknown"); + const VersionInfo info = Parser::parse("0+unknown"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("0", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -16,7 +16,7 @@ TEST(ParserTest, TestUnknownVersion) { } TEST(ParserTest, TestReleaseVersion_1) { - VersionInfo info = Parser::parse("0.9.2"); + const VersionInfo info = Parser::parse("0.9.2"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("2", info.hotfixVersion); @@ -28,7 +28,7 @@ TEST(ParserTest, TestReleaseVersion_1) { } TEST(ParserTest, TestReleaseVersion_2) { - VersionInfo info = Parser::parse("1.02.3"); + const VersionInfo info = Parser::parse("1.02.3"); EXPECT_EQ("1", info.majorVersion); EXPECT_EQ("02", info.minorVersion); EXPECT_EQ("3", info.hotfixVersion); @@ -40,7 +40,7 @@ TEST(ParserTest, TestReleaseVersion_2) { } TEST(ParserTest, TestReleaseVersion_3) { - VersionInfo info = Parser::parse("01.020.3"); + const VersionInfo info = Parser::parse("01.020.3"); EXPECT_EQ("01", info.majorVersion); EXPECT_EQ("020", info.minorVersion); EXPECT_EQ("3", info.hotfixVersion); @@ -52,7 +52,7 @@ TEST(ParserTest, TestReleaseVersion_3) { } TEST(ParserTest, TestDirtyReleaseVersion) { - VersionInfo info = Parser::parse("0.9.0+0.g5753e4f.dirty"); + const VersionInfo info = Parser::parse("0.9.0+0.g5753e4f.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -65,7 +65,7 @@ TEST(ParserTest, TestDirtyReleaseVersion) { TEST(ParserTest, TestDevVersion) { - VersionInfo info = Parser::parse("0.9.0+2.g0123abcdef"); + const VersionInfo info = Parser::parse("0.9.0+2.g0123abcdef"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -77,7 +77,7 @@ TEST(ParserTest, TestDevVersion) { } TEST(ParserTest, TestDirtyDevVersion) { - VersionInfo info = Parser::parse("0.9.0+20.g0123abcdef.dirty"); + const VersionInfo info = Parser::parse("0.9.0+20.g0123abcdef.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -89,7 +89,7 @@ TEST(ParserTest, TestDirtyDevVersion) { } TEST(ParserTest, TestReleaseVersion_StableTag) { - VersionInfo info = Parser::parse("0.9.2-stable"); + const VersionInfo info = Parser::parse("0.9.2-stable"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("2", info.hotfixVersion); @@ -101,7 +101,7 @@ TEST(ParserTest, TestReleaseVersion_StableTag) { } TEST(ParserTest, TestDirtyReleaseVersion_StableTag) { - VersionInfo info = Parser::parse("0.9.0-stable+0.g5753e4f.dirty"); + const VersionInfo info = Parser::parse("0.9.0-stable+0.g5753e4f.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -113,7 +113,7 @@ TEST(ParserTest, TestDirtyReleaseVersion_StableTag) { } TEST(ParserTest, TestDevVersion_StableTag) { - VersionInfo info = Parser::parse("0.9.0-stable+2.g0123abcdef"); + const VersionInfo info = Parser::parse("0.9.0-stable+2.g0123abcdef"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -125,7 +125,7 @@ TEST(ParserTest, TestDevVersion_StableTag) { } TEST(ParserTest, TestDirtyDevVersion_StableTag) { - VersionInfo info = Parser::parse("0.9.0-stable+20.g0123abcdef.dirty"); + const VersionInfo info = Parser::parse("0.9.0-stable+20.g0123abcdef.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -137,7 +137,7 @@ TEST(ParserTest, TestDirtyDevVersion_StableTag) { } TEST(ParserTest, TestReleaseVersion_AlphaTag) { - VersionInfo info = Parser::parse("0.9.2-alpha"); + const VersionInfo info = Parser::parse("0.9.2-alpha"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("2", info.hotfixVersion); @@ -149,7 +149,7 @@ TEST(ParserTest, TestReleaseVersion_AlphaTag) { } TEST(ParserTest, TestDirtyReleaseVersion_AlphaTag) { - VersionInfo info = Parser::parse("0.9.0-alpha+0.g5753e4f.dirty"); + const VersionInfo info = Parser::parse("0.9.0-alpha+0.g5753e4f.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -161,7 +161,7 @@ TEST(ParserTest, TestDirtyReleaseVersion_AlphaTag) { } TEST(ParserTest, TestDevVersion_AlphaTag) { - VersionInfo info = Parser::parse("0.9.0-alpha+2.g0123abcdef"); + const VersionInfo info = Parser::parse("0.9.0-alpha+2.g0123abcdef"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -173,7 +173,7 @@ TEST(ParserTest, TestDevVersion_AlphaTag) { } TEST(ParserTest, TestDirtyDevVersion_AlphaTag) { - VersionInfo info = Parser::parse("0.9.0-alpha+20.g0123abcdef.dirty"); + const VersionInfo info = Parser::parse("0.9.0-alpha+20.g0123abcdef.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -185,7 +185,7 @@ TEST(ParserTest, TestDirtyDevVersion_AlphaTag) { } TEST(ParserTest, TestReleaseVersion_WithoutHotfixVersion) { - VersionInfo info = Parser::parse("1.0-beta"); + const VersionInfo info = Parser::parse("1.0-beta"); EXPECT_EQ("1", info.majorVersion); EXPECT_EQ("0", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -197,7 +197,7 @@ TEST(ParserTest, TestReleaseVersion_WithoutHotfixVersion) { } TEST(ParserTest, TestReleaseVersion_RCTag) { - VersionInfo info = Parser::parse("0.9.2-rc1"); + const VersionInfo info = Parser::parse("0.9.2-rc1"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("2", info.hotfixVersion); @@ -209,7 +209,7 @@ TEST(ParserTest, TestReleaseVersion_RCTag) { } TEST(ParserTest, TestDirtyReleaseVersion_RCTag) { - VersionInfo info = Parser::parse("0.9.0-rc1+0.g5753e4f.dirty"); + const VersionInfo info = Parser::parse("0.9.0-rc1+0.g5753e4f.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -221,7 +221,7 @@ TEST(ParserTest, TestDirtyReleaseVersion_RCTag) { } TEST(ParserTest, TestDevVersion_RCTag) { - VersionInfo info = Parser::parse("0.9.0-rc1+2.g0123abcdef"); + const VersionInfo info = Parser::parse("0.9.0-rc1+2.g0123abcdef"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -233,7 +233,7 @@ TEST(ParserTest, TestDevVersion_RCTag) { } TEST(ParserTest, TestDirtyDevVersion_RCTag) { - VersionInfo info = Parser::parse("0.9.0-rc1+20.g0123abcdef.dirty"); + const VersionInfo info = Parser::parse("0.9.0-rc1+20.g0123abcdef.dirty"); EXPECT_EQ("0", info.majorVersion); EXPECT_EQ("9", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion); @@ -245,7 +245,7 @@ TEST(ParserTest, TestDirtyDevVersion_RCTag) { } TEST(ParserTest, TestDirtyDevVersion_WithoutMinorVersion) { - VersionInfo info = Parser::parse("1-rc1+20.g0123abcdef.dirty"); + const VersionInfo info = Parser::parse("1-rc1+20.g0123abcdef.dirty"); EXPECT_EQ("1", info.majorVersion); EXPECT_EQ("0", info.minorVersion); EXPECT_EQ("0", info.hotfixVersion);