# Path: raspi/scripts/get_serial.py
# def get_configuration(filename):
#     config_dict = {}
#     with open(filename, "r") as file_:
#         parser = ConfigParser.ConfigParser()
#         parser.readfp(file_)
#         config_dict["baudrate"] = parser.getint("config", "baudrate")
#         config_dict["tty_file"] = parser.get("config", "tty_file")
#         config_dict["data_path"] = parser.get("config", "data_path")
#         config_dict["refresh_rate"] = parser.getint("config", "refresh_rate")
#     return config_dict
# 
# def get_serial(config_type):
#     try:
#         config_path = {
#             "prod": "/etc/b2c/script_config",
#             "testing": "/etc/b2c/script_testing_config",
#             "testing_bg": "/etc/b2c/script_testing_config"
#         }[config_type]
#     except KeyError:
#         raise Exception("Configuration type not valid. Choose one of {}".format(config_path.keys()))
#     config = get_configuration(config_path)
#     # open port, set baudrate
#     ser = serial.Serial(port=config["tty_file"], baudrate=config["baudrate"])
#     flush_serial_buffers(ser)
#     while True:
#         # Wait until we have something to collect. If not sleep momentarily
#         if ser.inWaiting() == 0:
#             time.sleep(0.2)
#             continue
#         now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S.%f")
#         filename = str(socket.gethostname() +  "-" + now)
#         filename = os.path.join(os.path.abspath(config["data_path"]), filename)
#         filename = filename + ".csv"
#         retrieve_data(filename, config, ser)
#         flush_serial_buffers(ser)  # not too sure why we want to have this behavior but ok
#         if config_type == "testing":
#             break


from copy import copy
from tempfile import NamedTemporaryFile
from mock import MagicMock, patch
from nose.tools import assert_dict_equal, eq_
from raspi.scripts.get_serial import get_configuration, get_serial
            with patch("raspi.scripts.get_serial.open") as mock_open:
                with patch("raspi.scripts.get_serial.set_file_permissions"):
                    patched_config = copy(MOCK_CONFIG)
                    patched_config["refresh_rate"] = 1000  # An arbitrarily large number
                    get_config.return_value = patched_config
                    mock_file = MagicMock()
                    mock_open.return_value = mock_file
                    mock_serial_reader = MagicMock()
                    mock_serial_reader.readline.return_value = MOCK_SERIAL_RESPONSE
                    mock_serial.Serial.return_value = mock_serial_reader
                    mock_serial_reader.inWaiting.side_effect = lambda: vent_disc_iterator.next()
                    get_serial("testing")
                    last_line_written = mock_file.__enter__().write.call_args_list[-1][0][0]
                    eq_(last_line_written, MOCK_SERIAL_RESPONSE)
                    eq_(mock_open.call_count, 1)
                    # Writes once for the datetime, the next for the data
                    eq_(mock_file.__enter__().write.call_count, 2)


def test_get_serial_on_no_data_in_serial_buffer():
    with patch("raspi.scripts.get_serial.get_configuration") as get_config:
        with patch("raspi.scripts.get_serial.serial") as mock_serial:
            with patch("raspi.scripts.get_serial.open") as mock_open:
                with patch("raspi.scripts.get_serial.retrieve_data") as mock_retriever:
                    get_config.return_value = MOCK_CONFIG
                    mock_file = MagicMock()
                    mock_open.return_value = mock_file
                    mock_serial_reader = MagicMock()
                    mock_serial.Serial.return_value = mock_serial_reader
                    mock_serial_reader.inWaiting.return_value = 0

# Path: raspi/scripts/get_serial.py
# def get_configuration(filename):
#     config_dict = {}
#     with open(filename, "r") as file_:
#         parser = ConfigParser.ConfigParser()
#         parser.readfp(file_)
#         config_dict["baudrate"] = parser.getint("config", "baudrate")
#         config_dict["tty_file"] = parser.get("config", "tty_file")
#         config_dict["data_path"] = parser.get("config", "data_path")
#         config_dict["refresh_rate"] = parser.getint("config", "refresh_rate")
#     return config_dict
# 
# def get_serial(config_type):
#     try:
#         config_path = {
#             "prod": "/etc/b2c/script_config",
#             "testing": "/etc/b2c/script_testing_config",
#             "testing_bg": "/etc/b2c/script_testing_config"
#         }[config_type]
#     except KeyError:
#         raise Exception("Configuration type not valid. Choose one of {}".format(config_path.keys()))
#     config = get_configuration(config_path)
#     # open port, set baudrate
#     ser = serial.Serial(port=config["tty_file"], baudrate=config["baudrate"])
#     flush_serial_buffers(ser)
#     while True:
#         # Wait until we have something to collect. If not sleep momentarily
#         if ser.inWaiting() == 0:
#             time.sleep(0.2)
#             continue
#         now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S.%f")
#         filename = str(socket.gethostname() +  "-" + now)
#         filename = os.path.join(os.path.abspath(config["data_path"]), filename)
#         filename = filename + ".csv"
#         retrieve_data(filename, config, ser)
#         flush_serial_buffers(ser)  # not too sure why we want to have this behavior but ok
#         if config_type == "testing":
#             break


# Path: raspi/tests/test_get_serial.py
from copy import copy
from tempfile import NamedTemporaryFile
from mock import MagicMock, patch
from nose.tools import assert_dict_equal, eq_
from raspi.scripts.get_serial import get_configuration, get_serial

            with patch("raspi.scripts.get_serial.open") as mock_open:
                with patch("raspi.scripts.get_serial.set_file_permissions"):
                    patched_config = copy(MOCK_CONFIG)
                    patched_config["refresh_rate"] = 1000  # An arbitrarily large number
                    get_config.return_value = patched_config
                    mock_file = MagicMock()
                    mock_open.return_value = mock_file
                    mock_serial_reader = MagicMock()
                    mock_serial_reader.readline.return_value = MOCK_SERIAL_RESPONSE
                    mock_serial.Serial.return_value = mock_serial_reader
                    mock_serial_reader.inWaiting.side_effect = lambda: vent_disc_iterator.next()
                    get_serial("testing")
                    last_line_written = mock_file.__enter__().write.call_args_list[-1][0][0]
                    eq_(last_line_written, MOCK_SERIAL_RESPONSE)
                    eq_(mock_open.call_count, 1)
                    # Writes once for the datetime, the next for the data
                    eq_(mock_file.__enter__().write.call_count, 2)


def test_get_serial_on_no_data_in_serial_buffer():
    with patch("raspi.scripts.get_serial.get_configuration") as get_config:
        with patch("raspi.scripts.get_serial.serial") as mock_serial:
            with patch("raspi.scripts.get_serial.open") as mock_open:
                with patch("raspi.scripts.get_serial.retrieve_data") as mock_retriever:
                    get_config.return_value = MOCK_CONFIG
                    mock_file = MagicMock()
                    mock_open.return_value = mock_file
                    mock_serial_reader = MagicMock()
                    mock_serial.Serial.return_value = mock_serial_reader
                    mock_serial_reader.inWaiting.return_value = 0

                    get_serial("testing")