DEV Community

Kevin Albertson
Kevin Albertson

Posted on

Test Driven Learning

Idea: learn a new code base by writing tests. Read all of the public API. Come up with questions and try to answer them by writing tests.

I tried this idea with the libbson. I help maintain libbson. I was curious to see what (if anything) I would learn by surveying and testing the public API.

This is a summary of the results.

Discover API

I learned about the existence of the following:

  • BCON_EXTRACT to extract values from a bson_t.
  • bson_unichar_t and related API to represent a Unicode codepoint in a uint32_t.
  • bson_writer_t to write a sequence of BSON documents to a buffer.

Find Surprising Behavior

bson_copy_to (<stack allocated>, <heap allocated>) results in a leak. For example:

static void test_bson_copy_to(void) {
    bson_t *dst = bson_new(); // dst is heap allocated.
    bson_t src = BSON_INITIALIZER; // src is stack allocated.
    BCON_APPEND(&src, "a", BCON_INT32(1));
    bson_copy_to(&src, dst); // struct for `bson_t` is leaked!
    ASSERT_BSON_EQUAL(&src, dst);
    bson_destroy(&src);
    bson_destroy(dst);
}
Enter fullscreen mode Exit fullscreen mode

bson_validate double validates UTF-8 values. bson_iter_visit_all validates UTF-8, as does the visitor functions.

Found that BSON_CHECK_VERSION is incorrectly documented. "is greater than" should be "is greater than or equal to". Fixed with (https://github.com/mongodb/mongo-c-driver/pull/1219).

Answer Open Questions

As I read through API, I wrote down many open questions and answered them with tests:

  • Q: Does bson_append_array reject documents with non integer string keys?

    • A: No. But bson_append_array warns if the first key is not "0".
  • Q: Does bson_append_utf8 error if given invalid UTF-8? A: No.

  • Q: If the default bson_context_t is used, is a child process likely to produce the same bson_oid_t?

    • A: No. The default bson_context_t disables the PID cache.
  • Q: Does the max len option of bson_json_opts_new produce invalid UTF-8 characters if on multi-byte character boundary? A: Yes.

  • Q: Does bson_concat support self-concatenation? A: Yes

  • Q: Can bson_iter_find_descendant and bson_iter_recurse use the same iterator for input and output? A: Yes

  • Q: Will parsing an integer value in JSON promote to int64 if it does not fit in int32? A: Yes.

  • Q: How does bson_string_t grow allocations? A: By power of 2.

Learn more C

Learned about static keyword applied to array sizes: https://hamberg.no/erlend/posts/2013-02-18-static-array-indices.html

Learned that aligned_alloc requires alignment to be a power of 2 >= sizeof(void*), and memory requested be a multiple of alignment.

Conclusion

I think this was a valuable time investment.

For further reading, I recommend David Golden's A better way to learn a new codebase. That article inspired this idea.

Top comments (0)