|
1 | | -# 🚀 PCB Backend API - Unit Testing Branch |
| 1 | +# 🚀 PCB Backend API |
2 | 2 |
|
3 | | -> **Note**: This is the dedicated branch for **setup and validation of unit tests**. |
4 | | -> If you are looking for the production documentation, please switch to the `main` branch. |
| 3 | +Backend service yang handal untuk sistem IoT PCB, dibangun menggunakan **FastAPI** (Python). Proyek ini menyediakan API untuk manajemen perangkat, kontrol relay secara real-time via **MQTT**, penyimpanan log sensor, dan autentikasi pengguna yang aman. |
5 | 4 |
|
6 | | -This branch focuses on ensuring code stability and reliability using `pytest` with a **Mocked Environment** strategy. |
| 5 | +--- |
| 6 | + |
| 7 | +## ✨ Fitur Utama |
| 8 | + |
| 9 | +* **⚡ High Performance API**: Dibangun di atas FastAPI (Asynchronous). |
| 10 | +* **🔐 Secure Authentication**: Terintegrasi penuh dengan **Firebase Auth** (Token Validation). |
| 11 | +* **📡 Real-time Control**: Kontrol perangkat (Lampu, Pompa, dll) menggunakan protokol **MQTT**. |
| 12 | +* **🗄️ Database Power**: Menggunakan **PostgreSQL** untuk data persisten yang handal. |
| 13 | +* **🛡️ Rate Limiting**: Perlindungan terhadap spam/brute-force menggunakan **Redis**. |
| 14 | +* **🐳 Dockerized**: Mudah di-deploy menggunakan Docker Compose. |
| 15 | +* **🤖 Auto Register**: Mekanisme pendaftaran otomatis untuk perangkat keras (ESP32) yang valid. |
7 | 16 |
|
8 | 17 | --- |
9 | 18 |
|
10 | | -## 🧪 Testing Features |
11 | | -This branch implements a robust testing suite that covers: |
12 | | -* **Auto-Registration**: Validates ESP32 device registration flow. |
13 | | -* **Device Claiming**: Ensures user ownership claim logic works safely. |
14 | | -* **Mqtt Controls**: Mocks MQTT publishing to verify command logic without real broker connection. |
15 | | -* **Rate Limiting**: Tests protection mechanisms against spamming. |
| 19 | +## 🛠️ Teknologi yang Digunakan |
16 | 20 |
|
17 | | -### Why Mocking? |
18 | | -We use `mock` and `patch` to isolate the backend from external dependencies: |
19 | | -1. **NO Real Database**: Uses `sqlite:///:memory:` for fast, clean-slate testing. |
20 | | -2. **NO Real MQTT**: Connection is intercepted to prevent network errors. |
21 | | -3. **NO Real Redis**: Rate limits are bypassed or mocked for consistent results. |
| 21 | +* **Bahasa**: Python 3.11+ |
| 22 | +* **Framework**: FastAPI + Uvicorn |
| 23 | +* **Database**: PostgreSQL |
| 24 | +* **Cache & Limiter**: Redis |
| 25 | +* **Messaging**: Paho MQTT |
| 26 | +* **Auth**: Firebase Admin SDK |
| 27 | +* **DevOps**: Docker & Docker Compose |
22 | 28 |
|
23 | 29 | --- |
24 | 30 |
|
25 | | -## 📋 Prerequisites |
26 | | -Ensure you have the following installed: |
27 | | -1. **Python 3.11+** |
28 | | -2. **Virtual Environment (`venv`)** |
| 31 | +## 📋 Prasyarat |
| 32 | + |
| 33 | +Sebelum memulai, pastikan Anda telah menginstal: |
| 34 | + |
| 35 | +1. **Docker** & **Docker Compose** (Sangat Disarankan) |
| 36 | +2. **Git** |
| 37 | +3. Akun **Firebase** (untuk Authentication dan `serviceAccountKey.json`) |
| 38 | +4. **Python 3.11+** (Untuk Development/Testing lokal) |
29 | 39 |
|
30 | 40 | --- |
31 | 41 |
|
32 | | -## 🚀 Setup & Installation |
| 42 | +## 🚀 Instalasi & Menjalankan (Docker) |
33 | 43 |
|
34 | | -### 1. Clone & Switch Branch |
| 44 | +Cara termudah untuk menjalankan proyek ini adalah menggunakan Docker Compose. |
| 45 | + |
| 46 | +### 1. Clone Repository |
35 | 47 | ```bash |
36 | | -git clone https://github.com/username/API-PCB.git |
| 48 | +git clone https://github.com/username/project-ini.git |
37 | 49 | cd API-PCB |
38 | | -git checkout unit-testing |
39 | 50 | ``` |
40 | 51 |
|
41 | | -### 2. Create Virtual Environment |
| 52 | +### 2. Konfigurasi Firebase |
| 53 | +Simpan file kredensial Firebase Admin SDK Anda ke lokasi berikut: |
42 | 54 | ```bash |
43 | | -python -m venv .venv |
44 | | -source .venv/bin/activate # On Windows: .venv\Scripts\activate |
| 55 | +app/serviceAccountKey.json |
| 56 | +``` |
| 57 | +> **Penting**: File ini bersifat rahasia. Jangan pernah commit file ini ke repository publik! |
| 58 | +
|
| 59 | +### 3. Konfigurasi Environment Variable |
| 60 | +Buat file `.env` di root folder dan sesuaikan isinya: |
| 61 | + |
| 62 | +```env |
| 63 | +# Database Credentials |
| 64 | +DB_USER=iot_user |
| 65 | +DB_PASSWORD=iot_password |
| 66 | +DB_NAME=iot_db |
| 67 | +
|
| 68 | +# Redis URL (Default Docker) |
| 69 | +REDIS_URL=redis://redis:6379/0 |
| 70 | +
|
| 71 | +# (Opsional) Lainnya sesuai kebutuhan |
45 | 72 | ``` |
46 | 73 |
|
47 | | -### 3. Install Requirements |
48 | | -Install main dependencies + testing libraries (`pytest`, `httpx`, etc.): |
| 74 | +### 4. Jalankan Aplikasi |
49 | 75 | ```bash |
50 | | -pip install -r requirements.txt |
| 76 | +docker-compose up -d --build |
51 | 77 | ``` |
| 78 | +Aplikasi akan berjalan di: |
| 79 | +* **API**: `http://localhost:8006` |
| 80 | +* **Swagger Docs**: `http://localhost:8006/docs` |
| 81 | +* **Redoc**: `http://localhost:8006/redoc` |
52 | 82 |
|
53 | 83 | --- |
54 | 84 |
|
55 | | -## ⚙️ Running Tests |
| 85 | +## 📡 Dokumentasi API |
56 | 86 |
|
57 | | -### Standard Run |
58 | | -Simply execute `pytest` from the root directory. It will automatically load configuration from `tests/conftest.py`. |
| 87 | +Seluruh endpoint membutuhkan **Header Authorization** (Bearer Token dari Firebase Client), kecuali endpoint *Auto Register*. |
59 | 88 |
|
60 | | -```bash |
61 | | -pytest |
62 | | -``` |
| 89 | +### 📱 1. Device Management (`/api/devices`) |
63 | 90 |
|
64 | | -**Expected Output (Greens):** |
65 | | -``` |
66 | | -tests/test_devices.py ...... [100%] |
67 | | -================= 6 passed in 0.xxs ================= |
68 | | -``` |
| 91 | +| Method | Endpoint | Deskripsi | Limit Rate | |
| 92 | +| :--- | :--- | :--- | :--- | |
| 93 | +| `GET` | `/my-devices` | Mengambil daftar alat milik user. | 20/menit | |
| 94 | +| `POST` | `/claim` | Mengklaim alat baru menggunakan ID & PIN. | 5/menit | |
| 95 | +| `PUT` | `/{device_id}` | Mengubah nama alat. | 10/menit | |
| 96 | +| `DELETE` | `/{device_id}` | Menghapus alat dari akun (Unclaim). | 5/menit | |
69 | 97 |
|
70 | | -### Run with Detailed Output |
71 | | -To see printed logs (e.g. "Mock MQTT Publish"): |
72 | | -```bash |
73 | | -pytest -s |
74 | | -``` |
| 98 | +### 🎛️ 2. Device Control (`/api/devices`) |
| 99 | + |
| 100 | +| Method | Endpoint | Deskripsi | Parameter | |
| 101 | +| :--- | :--- | :--- | :--- | |
| 102 | +| `POST` | `/control-relay` | Mengirim perintah ON/OFF ke alat via MQTT. | `device_id`, `relay_name`, `state` (bool) | |
| 103 | +| `POST` | `/auto-register` | (Internal) Pendaftaran otomatis oleh ESP32. | *Requires Factory Secret* | |
| 104 | + |
| 105 | +> **Relay Mapping**: |
| 106 | +> * `relay_1` -> Topik `.../cmd/lampu` |
| 107 | +> * `relay_2` -> Topik `.../cmd/pompa_minum` |
| 108 | +> * `relay_3` -> Topik `.../cmd/pompa_siram` |
| 109 | +
|
| 110 | +### 📊 3. Sensor Logs (`/api/logs`) |
| 111 | + |
| 112 | +| Method | Endpoint | Deskripsi | |
| 113 | +| :--- | :--- | :--- | |
| 114 | +| `GET` | `/{device_id}` | Mengambil data log sensor dari alat tertentu. | |
| 115 | + |
| 116 | +--- |
| 117 | + |
| 118 | +## 📂 Struktur Proyek |
75 | 119 |
|
76 | | -### Run Specific Test |
77 | | -```bash |
78 | | -pytest tests/test_devices.py::test_auto_register_success |
| 120 | +``` |
| 121 | +API-PCB/ |
| 122 | +├── app/ |
| 123 | +│ ├── api/ # Router & Logic API per versi (v1) |
| 124 | +│ │ └── v1/ |
| 125 | +│ │ ├── auth.py # Helper Auth Firebase |
| 126 | +│ │ ├── devices.py # Endpoint Device & Control |
| 127 | +│ │ └── logs.py # Endpoint Logs |
| 128 | +│ ├── core/ # Konfigurasi Database & Global |
| 129 | +│ ├── crud/ # Operasi Database (Create, Read, etc) |
| 130 | +│ ├── models/ # Schema Database (SQLAlchemy) |
| 131 | +│ ├── mqtt/ # Client & Handler MQTT |
| 132 | +│ ├── schemas/ # Validasi Data (Pydantic) |
| 133 | +│ ├── main.py # Entry Point Aplikasi (Lifespan, Startup) |
| 134 | +│ └── serviceAccountKey.json # (WAJIB ADA) Kunci Firebase |
| 135 | +├── tests/ # 🧪 Unit Tests (Pytest) |
| 136 | +│ ├── conftest.py # Mock Config |
| 137 | +│ └── test_devices.py # Tests |
| 138 | +├── docker-compose.yml # Orkestrasi Container (App, DB, Redis) |
| 139 | +├── dockerfile # Definisi Image App |
| 140 | +├── requirements.txt # Dependensi Python |
| 141 | +├── test_client.py # Script Python untuk mencoba API manual |
| 142 | +└── readme.md # Dokumentasi ini |
79 | 143 | ``` |
80 | 144 |
|
81 | 145 | --- |
82 | 146 |
|
83 | | -## 📂 Test Structure |
84 | | -* **`tests/`**: Contains all test modules. |
85 | | - * **`conftest.py`**: The heart of the test setup. Contains: |
86 | | - * `load_dotenv()`: Auto-load `.env` variables. |
87 | | - * `mock_external_services`: Fixture to patch MQTT, Redis, Firebase. |
88 | | - * `db_session`: Fixture to create/drop pure in-memory SQLite tables. |
89 | | - * **`test_devices.py`**: Functional tests for device endpoints. |
| 147 | +## 🧪 Testing |
| 148 | + |
| 149 | +Proyek ini mendukung **Unit Testing Otomatis** dan **Testing Manual**. |
| 150 | + |
| 151 | +### 🤖 1. Unit Testing (Automated) |
| 152 | + |
| 153 | +Kami menggunakan `pytest` dengan sistem **Mocking** agar tidak perlu koneksi ke database asli, MQTT broker, atau Firebase. |
| 154 | + |
| 155 | +#### Prasyarat |
| 156 | +* Python 3.11+ |
| 157 | +* Virtual Environment |
| 158 | + |
| 159 | +#### Cara Menjalankan |
| 160 | +1. **Setup Environment**: |
| 161 | + ```bash |
| 162 | + python -m venv .venv |
| 163 | + source .venv/bin/activate |
| 164 | + pip install -r requirements.txt |
| 165 | + ``` |
| 166 | +2. **Jalankan Test**: |
| 167 | + ```bash |
| 168 | + pytest |
| 169 | + ``` |
| 170 | +3. **Hasil**: |
| 171 | + Anda akan melihat laporan sukses (hijau) jika seluruh fungsi berjalan normal. |
| 172 | + |
| 173 | +#### Fitur Mock |
| 174 | +Test ini **tidak** menyentuh production, karena: |
| 175 | +* **Database**: Menggunakan SQLite In-Memory. |
| 176 | +* **MQTT**: Dipalsukan dengan `MagicMock`. |
| 177 | +* **Redis/Auth**: Di-bypass menggunakan Dependency Injection Override. |
| 178 | + |
| 179 | +### 👨💻 2. Testing Manual (`test_client.py`) |
| 180 | + |
| 181 | +Terdapat script `test_client.py` untuk mencoba API secara real ke server (butuh Firebase Token asli). |
| 182 | + |
| 183 | +1. Pastikan `requests` terinstall: `pip install requests` |
| 184 | +2. Edit `test_client.py`: |
| 185 | + * Masukkan `FIREBASE_WEB_API_KEY` (dari Firebase Console). |
| 186 | + * Masukkan credentials user dummy (Email/Pass). |
| 187 | + * Set `DEVICE_ID` target. |
| 188 | +3. Jalankan: |
| 189 | + ```bash |
| 190 | + python test_client.py |
| 191 | + ``` |
90 | 192 |
|
91 | 193 | --- |
92 | 194 |
|
93 | | -## 🔧 Troubleshooting |
94 | | -If tests fail: |
95 | | -1. **Check `.venv`**: Ensure it's active (`source .venv/bin/activate`). |
96 | | -2. **Requirements**: Run `pip install -r requirements.txt` again. |
97 | | -3. **Environment**: `conftest.py` should handle env vars, but ensure `.env` file exists if your app code critically depends on checking file existence. |
| 195 | +## 🤝 Kontribusi |
| 196 | + |
| 197 | +Pull requests dipersilakan. Untuk perubahan besar, harap buka issue terlebih dahulu untuk mendiskusikan apa yang ingin Anda ubah. |
98 | 198 |
|
99 | 199 | --- |
100 | 200 |
|
101 | | -**Happy Testing!** 🧪 |
| 201 | +**Happy Coding!** 🚀 |
0 commit comments