/** * @file test_semaphore.c * @brief Unit tests for semaphore */ #include "unity.h" #include "kernel.h" #include "semaphore.h" #include /* Test semaphores */ static Semaphore_t binary_sem; static Semaphore_t counting_sem; static Semaphore_t mutex_sem; /* Setup */ void setUp(void) { kernel_init(); /* Create test semaphores */ semaphore_create(&binary_sem, SEMAPHORE_BINARY, 1, 1); semaphore_create(&counting_sem, SEMAPHORE_COUNTING, 0, 10); semaphore_create(&mutex_sem, SEMAPHORE_MUTEX, 1, 1); } /* Teardown */ void tearDown(void) { kernel_stop(); } /* ============================================================================ * Test Cases * ============================================================================ */ /** * @brief Test binary semaphore creation */ void test_binary_semaphore_create(void) { TEST_ASSERT_EQUAL(1, semaphore_get_count(&binary_sem)); } /** * @brief Test counting semaphore creation */ void test_counting_semaphore_create(void) { TEST_ASSERT_EQUAL(0, semaphore_get_count(&counting_sem)); } /** * @brief Test semaphore take and give */ void test_semaphore_take_give(void) { /* Take binary semaphore */ TEST_ASSERT_EQUAL(KERNEL_OK, semaphore_take(&binary_sem, 100)); TEST_ASSERT_EQUAL(0, semaphore_get_count(&binary_sem)); /* Give binary semaphore */ TEST_ASSERT_EQUAL(KERNEL_OK, semaphore_give(&binary_sem)); TEST_ASSERT_EQUAL(1, semaphore_get_count(&binary_sem)); } /** * @brief Test semaphore timeout */ void test_semaphore_timeout(void) { /* Take the only available semaphore */ TEST_ASSERT_EQUAL(KERNEL_OK, semaphore_take(&binary_sem, 0)); /* Try to take again with timeout */ TEST_ASSERT_EQUAL(KERNEL_TIMEOUT, semaphore_take(&binary_sem, 10)); } /** * @brief Test counting semaphore operations */ void test_counting_semaphore_operations(void) { /* Give multiple times */ for (int i = 0; i < 5; i++) { TEST_ASSERT_EQUAL(KERNEL_OK, semaphore_give(&counting_sem)); } TEST_ASSERT_EQUAL(5, semaphore_get_count(&counting_sem)); /* Take multiple times */ for (int i = 0; i < 3; i++) { TEST_ASSERT_EQUAL(KERNEL_OK, semaphore_take(&counting_sem, 0)); } TEST_ASSERT_EQUAL(2, semaphore_get_count(&counting_sem)); } /** * @brief Test semaphore deletion */ void test_semaphore_delete(void) { TEST_ASSERT_EQUAL(KERNEL_OK, semaphore_delete(&binary_sem)); TEST_ASSERT_EQUAL(0, semaphore_get_count(&binary_sem)); } /* ============================================================================ * Test Runner * ============================================================================ */ int main(void) { UNITY_BEGIN(); RUN_TEST(test_binary_semaphore_create); RUN_TEST(test_counting_semaphore_create); RUN_TEST(test_semaphore_take_give); RUN_TEST(test_semaphore_timeout); RUN_TEST(test_counting_semaphore_operations); RUN_TEST(test_semaphore_delete); return UNITY_END(); }