#coding utf8
#!/usr/bin/python

import os
import sys
import time
import binascii
import pymysql
import threading
import subprocess
from optparse import OptionParser

def printp_stdout(p):
    try:
        while True:
            line = p.stdout.readline()
            if len(line) > 0 and line != b'crc32test start\n':
                accountid, phpcrc32 = line.strip().decode('utf-8').split(' ')
                pycrc32 = str(binascii.crc32(accountid.encode('utf-8')))
                assert int(phpcrc32) < 0xFFFFFFFF
                assert phpcrc32 == pycrc32
                print(accountid + ' ' + phpcrc32 + ' ' + pycrc32 + '\n', end = '', flush = True)
    except Exception as e:
        print('crc32test stdout error:' + str(e), flush = True)

def printp_stderr(p):
    try:
        while True:
            line = p.stderr.readline()
            if len(line) > 0:
                print(line, end = '', flush = True)
    except Exception as e:
        print('crc32test stderr error:' + str(e), flush = True)

def printp_stdin(p):
    try:
        for i in range(1, 20):
            dbname = 'accountdb_bk' + str(i)
            db = pymysql.connect('127.0.0.1',
                                 'root',
                                 'keji178',
                                 dbname)
            cursor = db.cursor()
            cursor.execute('select accountid from accounts')
            for row in cursor.fetchall():
                p.stdin.write((row[0] + "\n").encode('utf-8'))
                p.stdin.flush()
    except Exception as e:
        print('crc32test stdin error:' + str(e), flush = True)

def run_test():
    try:
        p = subprocess.Popen(
            'php test.php',
            stdin = subprocess.PIPE,
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE,
            shell = True)
        t1 = threading.Thread(target = printp_stdout, args=(p, ))
        t2 = threading.Thread(target = printp_stderr, args=(p, ))
        t3 = threading.Thread(target = printp_stdin, args=(p, ))
        t1.start()
        t2.start()
        t3.start()
        p.wait()
        t1.join()
        t2.join()
        t3.join()
        sys.exit(p.returncode)
    except Exception as e:
        print('run_test error:' + str(e), flush = True)

run_test()
