1 /*
2 * Copyright 2024 Google LLC
3 * SPDX-License-Identifier: Apache-2.0
4 */
5 #include "emulated_target.hpp"
6
7 #include <zephyr/devicetree.h>
8 #include <zephyr/drivers/i2c.h>
9 #include <zephyr/fff.h>
10 #include <zephyr/ztest.h>
11
12 namespace
13 {
14
15 #define GET_TARGET_DEVICE(node_id, prop, n) DEVICE_DT_GET(DT_PHANDLE_BY_IDX(node_id, prop, n)),
16
17 /* Get the devicetree constants */
18 constexpr const struct device *controller = DEVICE_DT_GET(CONTROLLER_LABEL);
19 constexpr const struct device *targets[FORWARD_COUNT] = {
20 DT_FOREACH_PROP_ELEM(CONTROLLER_LABEL, forwards, GET_TARGET_DEVICE)};
21
i2c_emul_forwarding_setup(void)22 static void *i2c_emul_forwarding_setup(void)
23 {
24 // Register the target
25 for (int i = 0; i < FORWARD_COUNT; ++i) {
26 zassert_ok(i2c_target_register(targets[i], &emulated_target_config[i]));
27 }
28
29 return NULL;
30 }
31
i2c_emul_forwarding_before(void * fixture)32 static void i2c_emul_forwarding_before(void *fixture)
33 {
34 ARG_UNUSED(fixture);
35
36 // Reset all fakes
37 FFF_FAKES_LIST_FOREACH(RESET_FAKE);
38 FFF_RESET_HISTORY();
39 }
40
i2c_emul_forwarding_teardown(void * fixture)41 static void i2c_emul_forwarding_teardown(void *fixture)
42 {
43 ARG_UNUSED(fixture);
44
45 // Unregister the I2C target callbacks
46 for (int i = 0; i < FORWARD_COUNT; ++i) {
47 zassert_ok(i2c_target_unregister(targets[i], &emulated_target_config[i]));
48 }
49 }
50
51 ZTEST_SUITE(i2c_emul_forwarding, NULL, i2c_emul_forwarding_setup, i2c_emul_forwarding_before, NULL,
52 i2c_emul_forwarding_teardown);
53
54 /* Common tests */
55
ZTEST(i2c_emul_forwarding,test_invalid_address_for_target)56 ZTEST(i2c_emul_forwarding, test_invalid_address_for_target)
57 {
58 uint8_t data = 0;
59 int rc = i2c_write(targets[0], &data, 1, emulated_target_config[0].address + 1);
60 zassert_equal(-EINVAL, rc, "Expected %d (-EINVAL), but got %d", -EINVAL, rc);
61 zexpect_equal(0, target_read_requested_0_fake.call_count);
62 zexpect_equal(0, target_read_processed_0_fake.call_count);
63 zexpect_equal(0, target_write_requested_0_fake.call_count);
64 zexpect_equal(0, target_write_received_0_fake.call_count);
65 zexpect_equal(0, target_buf_write_received_0_fake.call_count);
66 zexpect_equal(0, target_buf_read_requested_0_fake.call_count);
67 zexpect_equal(0, target_stop_0_fake.call_count);
68 }
69
ZTEST(i2c_emul_forwarding,test_error_in_stop)70 ZTEST(i2c_emul_forwarding, test_error_in_stop)
71 {
72 uint8_t data = 0;
73
74 target_stop_0_fake.return_val = -EINTR;
75 zassert_equal(-EINTR, i2c_write(controller, &data, 1, emulated_target_config[0].address));
76 zexpect_equal(1, target_stop_0_fake.call_count);
77 }
78
79 } // namespace
80