/*
 * Unit test for data_source implementation
 */

#include "test.h" 
#include "libisofs.h"

#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void test_data_source_from_file()
{
	int res;
	struct data_source *ds;
	unsigned char buffer[2048];
	unsigned char rbuff[2048];
	char filename[] = "/tmp/temp.iso.XXXXXX";
	int fd = mkstemp(filename);
	
	/* actually a failure here means that we couldn't test */
	CU_ASSERT_NOT_EQUAL(fd, -1);
	
	memset(buffer, 0x35, 2048);
	write(fd, buffer, 2048);
	memset(buffer, 0x20, 2048);
	write(fd, buffer, 2048);
	memset(buffer, 0xF2, 2048);
	write(fd, buffer, 2048);
	memset(buffer, 0x11, 2048);
	write(fd, buffer, 2048);
	memset(buffer, 0xAB, 2048);
	write(fd, buffer, 2048);
	close(fd);
	
	ds = data_source_from_file(filename);
	CU_ASSERT_PTR_NOT_NULL(ds);
	
	/* check correct size reported */
	CU_ASSERT_EQUAL(ds->get_size(ds), 5);
	
	/* check reading */
	res = ds->read_block(ds, 4, rbuff);
	CU_ASSERT_EQUAL(res, 0);
	CU_ASSERT_NSTRING_EQUAL(rbuff, buffer, 2048);
	
	res = ds->read_block(ds, 1, rbuff);
	CU_ASSERT_EQUAL(res, 0);
	memset(buffer, 0x20, 2048);
	CU_ASSERT_NSTRING_EQUAL(rbuff, buffer, 2048);
	
	res = ds->read_block(ds, 0, rbuff);
	CU_ASSERT_EQUAL(res, 0);
	memset(buffer, 0x35, 2048);
	CU_ASSERT_NSTRING_EQUAL(rbuff, buffer, 2048);
	
	res = ds->read_block(ds, 3, rbuff);
	CU_ASSERT_EQUAL(res, 0);
	memset(buffer, 0x11, 2048);
	CU_ASSERT_NSTRING_EQUAL(rbuff, buffer, 2048);
	
	/* and a block outside file */
	res = ds->read_block(ds, 5, rbuff);
	CU_ASSERT_TRUE(res < 0);
	
	data_source_free(ds);
	unlink(filename);
}
 
void add_data_source_suite()
{
	CU_pSuite pSuite = CU_add_suite("DataSourceSuite", NULL, NULL);
	
	CU_add_test(pSuite, "test of data_source_from_file()", test_data_source_from_file);
}