#include "test.h"

#include <fstream>

#include "fd_line_provider.h"
#include "mock_log_lines.h"

TEST_CASE("read fd") {
	int fd[2];
	CHECK(!pipe(fd));

	list<string> data = {
		"hello", "there", "good", "people", "and",
		"welcome", "to", "the", "test"};

	MockLogLines ll;
	ll.expect(data);
	FDLineProvider fdlp(&ll, fd[0]);
	fdlp.start();

	for (const auto& x : data) {
		CHECK(x.size() == static_cast<size_t>(
			write(fd[1], x.data(), x.size())));
		CHECK(1 == write(fd[1], "\n", 1));
	}

	while (!ll.no_expectations()) {
		usleep(1000);
	}
	CHECK(ll.no_expectations());
	ll.expect("more data");
	ll.expect("and yet more");
	CHECK(10 == write(fd[1], "more data\n", 10));
	usleep(10000);
	CHECK(13 == write(fd[1], "and yet more\n", 13));
	while (!ll.no_expectations()) {
		usleep(1000);
	}
	// pipe is open
	CHECK(ll.eof() == false);
	close(fd[1]);
	while (!ll.eof()) usleep(100);
}
