import os
import subprocess
import unittest
import base64

class TransferDataTest(unittest.TestCase):
  def create_embulk_config(self, config, data_in_path, data_out_path):
    config_string = "exec:\n max_threads: 1\n min_output_tasks: 1\n" + \
      "in:\n type: filename\n path_prefix: %s\n parser:\n  type: none-bin\n" + \
      "out:\n type: file\n path_prefix: %s\n file_ext: wen\n formatter:\n  type: single_value"
      
    config_string = config_string % (data_in_path, data_out_path)
    f = open(config,'w')
    print >> f,config_string
    f.close()
  
  def test_transfer_data(self):
    pwd = os.getcwd()
    config = pwd[:len(pwd)-4] + "templates/config.yml"
    data_in_path = pwd[:len(pwd)-4] + "data_in/"
    data_out_path = pwd[:len(pwd)-4] + "data_out/data_out"
    
    # data_in = "It works"
    # data_in_file = data_in_path + "data-in.wen"
    # data_in_file = open(data_in_file, 'wb')
    # data_in_file.write(data_in)
    # data_in_file.close()
    
    self.create_embulk_config(config, data_in_path, data_out_path)
    subprocess.call(['/srv/slapgrid/slappart18/srv/runner/software/f5aec1c37c220000ab1c2ef799aac847/parts/java/bin/java',
      '-jar', '/srv/slapgrid/slappart18/srv/runner/software/f5aec1c37c220000ab1c2ef799aac847/parts/embulk/embulk.jar', 
      'run', config, '-b', '/srv/slapgrid/slappart18/srv/runner/software/f5aec1c37c220000ab1c2ef799aac847/parts/embulkPlugins/plugins'])
    
    data_in_file = data_in_path + "data-in.wen"
    data_in_file = open(data_in_file, 'rb')
    data_in = data_in_file.read()
    data_in_file.close()
    
    data_out_file = data_out_path + "000.00.wen"
    data_out_file = open(data_out_file, 'rb')
    data_out = data_out_file.read()
    data_out_file.close()

    self.assertEqual(data_in, base64.b64decode(data_out))

if __name__ == "__main__":
  suite = unittest.TestLoader().loadTestsFromTestCase(TransferDataTest)
  unittest.TextTestRunner(verbosity=3).run(suite)
