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 /* Get the devicetree constants */
16 constexpr const struct device *controller = DEVICE_DT_GET(CONTROLLER_LABEL);
17 constexpr const struct device *targets[FORWARD_COUNT] = {
18 	DT_FOREACH_PROP_ELEM_SEP(CONTROLLER_LABEL, forwards, DEVICE_DT_GET_BY_IDX, (,))};
19 
i2c_emul_forwarding_setup(void)20 static void *i2c_emul_forwarding_setup(void)
21 {
22 	// Register the target
23 	for (int i = 0; i < FORWARD_COUNT; ++i) {
24 		zassert_ok(i2c_target_register(targets[i], &emulated_target_config[i]));
25 	}
26 
27 	return NULL;
28 }
29 
i2c_emul_forwarding_before(void * fixture)30 static void i2c_emul_forwarding_before(void *fixture)
31 {
32 	ARG_UNUSED(fixture);
33 
34 	// Reset all fakes
35 	FFF_FAKES_LIST_FOREACH(RESET_FAKE);
36 	FFF_RESET_HISTORY();
37 }
38 
i2c_emul_forwarding_teardown(void * fixture)39 static void i2c_emul_forwarding_teardown(void *fixture)
40 {
41 	ARG_UNUSED(fixture);
42 
43 	// Unregister the I2C target callbacks
44 	for (int i = 0; i < FORWARD_COUNT; ++i) {
45 		zassert_ok(i2c_target_unregister(targets[i], &emulated_target_config[i]));
46 	}
47 }
48 
49 ZTEST_SUITE(i2c_emul_forwarding, NULL, i2c_emul_forwarding_setup, i2c_emul_forwarding_before, NULL,
50 	    i2c_emul_forwarding_teardown);
51 
52 /* Common tests */
53 
ZTEST(i2c_emul_forwarding,test_invalid_address_for_target)54 ZTEST(i2c_emul_forwarding, test_invalid_address_for_target)
55 {
56 	uint8_t data = 0;
57 	int rc = i2c_write(targets[0], &data, 1, emulated_target_config[0].address + 1);
58 	zassert_equal(-EINVAL, rc, "Expected %d (-EINVAL), but got %d", -EINVAL, rc);
59 	zexpect_equal(0, target_read_requested_0_fake.call_count);
60 	zexpect_equal(0, target_read_processed_0_fake.call_count);
61 	zexpect_equal(0, target_write_requested_0_fake.call_count);
62 	zexpect_equal(0, target_write_received_0_fake.call_count);
63 	zexpect_equal(0, target_buf_write_received_0_fake.call_count);
64 	zexpect_equal(0, target_buf_read_requested_0_fake.call_count);
65 	zexpect_equal(0, target_stop_0_fake.call_count);
66 }
67 
ZTEST(i2c_emul_forwarding,test_error_in_stop)68 ZTEST(i2c_emul_forwarding, test_error_in_stop)
69 {
70 	uint8_t data = 0;
71 
72 	target_stop_0_fake.return_val = -EINTR;
73 	zassert_equal(-EINTR, i2c_write(controller, &data, 1, emulated_target_config[0].address));
74 	zexpect_equal(1, target_stop_0_fake.call_count);
75 }
76 
77 } // namespace
78