I am writing unit test for my c++ project where there are many functions which call glibc functions (malloc, read, open, write, close etc.) and also some external library functions such as openssl (SHA256 functions).
For example, Following function computes SHA256 checksum of a given file. Now this function has several calls to standard/external library functions such as, fopen, SHA256_Init, malloc etc. Now how to stub calls to these functions as our main objective is to unit test SHA256file, not the functions which it calls.
int MyClass::SHA256File(const char *path, char outputBuffer[65])
{
FILE *file = fopen(path, "rb");
if(!file) {
throw exception("Failed to open file for SHA256 computation.");
}
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
if ( !SHA256_Init(&sha256) ) {
throw exception("SHA256_Init failed.");
}
const int bufSize = 32768;
unsigned char *buffer = (unsigned char*) malloc(bufSize);
int bytesRead = 0;
if(!buffer) {
throw exception("Failed to allocate buffer for SHA256 computation.");
}
while( fgets((char*)buffer, bufSize, file) != NULL ) {
curr_pos = ftell(file);
bytesRead = curr_pos - last_pos;
last_pos = curr_pos;
if( !SHA256_Update(&sha256, buffer, bytesRead) ) {
throw exception("SHA256_Update failed..");
}
}
if ( ferror(file) ) {
throw exception("Failed to read file for SHA256 computation.");
}
if( !SHA256_Final(hash, &sha256) ) {
throw exception("SHA256_Final failed..");
}
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++) {
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
fclose(file);
free(buffer);
return 0;
}
I got few pointers like glibcmock but would prefer to have some standard support if glibc/gmock can provide.
Thanks in advance.