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 "pw_crypto/sha256.h"
18 #include "pw_crypto/sha256_backend.h"
19 #include "pw_unit_test/framework.h"
20
21 namespace pw::crypto::sha256 {
22 namespace {
23
24 #define AS_BYTES(str) as_bytes(span(str, sizeof(str) - 1))
25
26 #define ASSERT_FAIL(expr) ASSERT_NE(OkStatus(), expr)
27
TEST(Sha256,HandlesBackendInitFailures)28 TEST(Sha256, HandlesBackendInitFailures) {
29 std::byte digest[kDigestSizeBytes];
30
31 backend::ClearError();
32 PW_TEST_ASSERT_OK(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
33
34 backend::InjectError(backend::ErrorKind::kInit);
35 ASSERT_FAIL(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
36 }
37
TEST(Sha256,HandlesBackendUpdateFailures)38 TEST(Sha256, HandlesBackendUpdateFailures) {
39 std::byte digest[kDigestSizeBytes];
40
41 backend::ClearError();
42 PW_TEST_ASSERT_OK(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
43
44 backend::InjectError(backend::ErrorKind::kUpdate);
45 ASSERT_FAIL(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
46 }
47
TEST(Sha256,HandlesBackendFinalFailures)48 TEST(Sha256, HandlesBackendFinalFailures) {
49 std::byte digest[kDigestSizeBytes];
50
51 backend::ClearError();
52 PW_TEST_ASSERT_OK(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
53
54 backend::InjectError(backend::ErrorKind::kFinal);
55 ASSERT_FAIL(Sha256().Update(AS_BYTES("blahblah")).Final(digest));
56 }
57
58 } // namespace
59 } // namespace pw::crypto::sha256
60