CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
Ardupilot

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: Ardupilot/ardupilot
Path: blob/master/libraries/AP_Common/tests/test_nmea_vaprint.cpp
Views: 1799
1
#include <AP_gtest.h>
2
#include <AP_HAL/UARTDriver.h>
3
#include <AP_Common/NMEA.h>
4
5
const AP_HAL::HAL& hal = AP_HAL::get_HAL();
6
static uint32_t count = 0;
7
8
void *malloc(size_t size) {
9
if (count == 1) {
10
return nullptr;
11
}
12
return calloc(size, 1);
13
}
14
15
// THAT IS UGLY HACK BUT IT WORKS ... it is just used to make print_vprintf return negative value.
16
class BufferPrinter : public AP_HAL::BetterStream {
17
public:
18
BufferPrinter(char* str, size_t size) :
19
_offs(0), _str(str), _size(size) {}
20
21
size_t write(uint8_t c) override { return 1; }
22
size_t write(const uint8_t *buffer, size_t size) override { return 1; }
23
24
size_t _offs;
25
char* const _str;
26
const size_t _size;
27
28
uint32_t available() override { return 0; }
29
bool read(uint8_t &c) override { return false; };
30
uint32_t txspace() override { return 0; }
31
bool discard_input() override { return false; }
32
};
33
34
void print_vprintf(AP_HAL::BetterStream *s, const char *fmt, va_list ap);
35
void print_vprintf(AP_HAL::BetterStream *s, const char *fmt, va_list ap) {
36
BufferPrinter* p = static_cast<BufferPrinter*>(s);
37
count++;
38
if (count < 3) {
39
p->_offs = 4;
40
return;
41
}
42
p->_offs = -1;
43
return;
44
}
45
46
class DummyUart: public AP_HAL::UARTDriver {
47
public:
48
bool is_initialized() override { return true; };
49
bool tx_pending() override { return false; };
50
uint32_t txspace() override { return _txspace; };
51
52
void set_txspace(uint32_t space) {
53
_txspace = space;
54
}
55
uint32_t _txspace;
56
protected:
57
void _begin(uint32_t baud, uint16_t rxSpace, uint16_t txSpace) override { };
58
ssize_t _read(uint8_t *buf, uint16_t size) override { return 0; };
59
void _end() override { };
60
void _flush() override { };
61
uint32_t _available() override { return 1; };
62
size_t _write(const uint8_t *buffer, size_t size) override { return 1; };
63
bool _discard_input() override { return false; }
64
};
65
66
static DummyUart test_uart;
67
68
TEST(NMEA, VAPrintf)
69
{
70
// test Malloc failure
71
EXPECT_FALSE(nmea_printf(&test_uart, "test"));
72
// test second vsnprintf failure;
73
EXPECT_FALSE(nmea_printf(&test_uart, "test"));
74
// test first vsnprintf failure;
75
EXPECT_FALSE(nmea_printf(&test_uart, "test"));
76
}
77
78
AP_GTEST_MAIN()
79
80