1 // Copyright 2021 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include <cstring>
16
17 #include "gtest/gtest.h"
18 #include "pw_crypto/sha256.h"
19 #include "pw_crypto/sha256_backend.h"
20
21 namespace pw::crypto::sha256 {
22 namespace {
23
24 #define AS_BYTES(str) std::as_bytes(std::span(str, sizeof(str) - 1))
25
26 #define ASSERT_OK(expr) ASSERT_EQ(OkStatus(), expr)
27 #define ASSERT_FAIL(expr) ASSERT_NE(OkStatus(), expr)
28
TEST(Sha256,HandlesBackendInitFailures)29 TEST(Sha256, HandlesBackendInitFailures) {
30 std::byte digest[kDigestSizeBytes];
31
32 backend::ClearError();
33 ASSERT_OK(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
34
35 backend::InjectError(backend::ErrorKind::kInit);
36 ASSERT_FAIL(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
37 }
38
TEST(Sha256,HandlesBackendUpdateFailures)39 TEST(Sha256, HandlesBackendUpdateFailures) {
40 std::byte digest[kDigestSizeBytes];
41
42 backend::ClearError();
43 ASSERT_OK(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
44
45 backend::InjectError(backend::ErrorKind::kUpdate);
46 ASSERT_FAIL(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
47 }
48
TEST(Sha256,HandlesBackendFinalFailures)49 TEST(Sha256, HandlesBackendFinalFailures) {
50 std::byte digest[kDigestSizeBytes];
51
52 backend::ClearError();
53 ASSERT_OK(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
54
55 backend::InjectError(backend::ErrorKind::kFinal);
56 ASSERT_FAIL(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
57 }
58
59 } // namespace
60 } // namespace pw::crypto::sha256
61