optional.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <pb_encode.h>
  2. #include <pb_decode.h>
  3. #include <unittests.h>
  4. #include "optional.pb.h"
  5. int main()
  6. {
  7. int status = 0;
  8. uint8_t buf[256];
  9. size_t msglen;
  10. COMMENT("Test encoding message with optional field")
  11. {
  12. pb_ostream_t stream = pb_ostream_from_buffer(buf, sizeof(buf));
  13. TestMessage msg = TestMessage_init_zero;
  14. msg.has_opt_int = true;
  15. msg.opt_int = 99;
  16. msg.normal_int = 100;
  17. msg.opt_int2 = 101;
  18. TEST(pb_encode(&stream, TestMessage_fields, &msg));
  19. msglen = stream.bytes_written;
  20. }
  21. COMMENT("Test decoding message with optional field")
  22. {
  23. pb_istream_t stream = pb_istream_from_buffer(buf, msglen);
  24. TestMessage msg = TestMessage_init_zero;
  25. /* These fields should be missing from the message
  26. * so the values wouldn't be overwritten. */
  27. msg.opt_int2 = 5;
  28. msg.normal_int2 = 6;
  29. TEST(pb_decode_noinit(&stream, TestMessage_fields, &msg));
  30. TEST(msg.has_opt_int);
  31. TEST(msg.opt_int == 99);
  32. TEST(msg.normal_int == 100);
  33. TEST(!msg.has_opt_int2);
  34. TEST(msg.opt_int2 == 5);
  35. TEST(msg.normal_int2 == 6);
  36. }
  37. return status;
  38. }