# -*- coding: utf-8 -*-
from homehub_backend.lib import services


class Test_ServiceData:
    def test_init(self):
        exc = RuntimeError('TODO')

        service_data = services.ServiceData(data='spam', exception=exc)
        assert service_data.data == 'spam'
        assert service_data.exception == exc

    def test_raise_if_needed_raise(self):
        exc = RuntimeError('TODO')

        service_data = services.ServiceData(data='spam', exception=exc)
        raised_exception = None
        try:
            service_data.raise_if_needed()
        except Exception as _exc:
            raised_exception = _exc

        assert raised_exception == exc, 'Did not raise?'

    def test_raise_if_needed_dont_raise(self):
        service_data = services.ServiceData(data='spam', exception=None)
        raised_exception = None
        try:
            service_data.raise_if_needed()
        except Exception as _exc:
            raised_exception = _exc

        assert raised_exception is None, f'Raised {raised_exception}'

    def test_to_json(self):
        exc = RuntimeError('TODO')
        service_data = services.ServiceData(data='spam', exception=exc)

        result = service_data.to_json()
        assert result['data'] == service_data.data
        assert result['error'] == exc.args[0]

    def test_to_json_no_data(self):
        exc = RuntimeError('TODO')
        service_data = services.ServiceData(data=None, exception=exc)

        result = service_data.to_json()
        assert 'data' not in result
        assert result['error'] == exc.args[0]

    def test_to_json_no_exception(self):
        service_data = services.ServiceData(data='spam', exception=None)

        result = service_data.to_json()
        assert result['data'] == service_data.data
        assert 'error' not in result
