import pytest
import asyncio
from common.state import State
from connection import logstash_connection
from common.config import config


@pytest.mark.asyncio
async def test_read_common_file(event_loop, unused_tcp_port):
    test = list()
    state = State()

    async def handler(reader, writer):
        while not state.need_shutdown:
            line = await reader.readline()
            if not line or line == b'':
                break
            test.append(line)
        done.set()
        writer.close()

    port = unused_tcp_port
    done = asyncio.Event()
    config['connection']['host'] = '127.0.0.1'
    config['connection']['port'] = port
    config['ssl']['enable'] = False
    queue = asyncio.Queue(loop=event_loop)
    await queue.put("Message 1\n")
    await queue.put("Message 2\n")
    await queue.put("Message 3\n")
    server = await asyncio.start_server(
        handler, host='127.0.0.1', port=port, loop=event_loop)
    client = asyncio.ensure_future(logstash_connection(
        queue, state, loop=event_loop))
    await queue.join()
    state.shutdown()
    await client
    await done.wait()
    assert len(test) == 3
    server.close()
    await server.wait_closed()

@@ -130,16 +130,29 @@
 config%0A%0A
+counter = 0%0A%0A
 %0A@pytest
@@ -264,16 +264,51 @@
  State()
+%0A    global counter%0A    counter = 0
 %0A%0A    as
@@ -340,16 +340,60 @@
 riter):%0A
+        global counter%0A        counter += 1%0A
         
@@ -528,16 +528,105 @@
   break%0A
+            if (counter %25 2) == 0:%0A                writer.close()%0A                return%0A
         
@@ -914,32 +914,77 @@
 op)%0A    
-await queue.put(
+test_messages = list()%0A%0A    for i in range(100):%0A        m = 
 %22Message
@@ -988,53 +988,64 @@
 age 
-1%5Cn%22)%0A    await queue.put(%22Message 2%5Cn%22)%0A
+%7B%7D%5Cn%22.format(i)%0A        test_messages.append(m)%0A   
     
+ 
 awai
@@ -1060,23 +1060,12 @@
 put(
-%22Message 3%5Cn%22
+m
 )%0A
+%0A
     
@@ -1371,9 +1371,26 @@
  == 
-3
+len(test_messages)
 %0A   

make test_connection to check restore connect after disconnect