Beispiel #1
0
def test_call():
    """Calling a command should result in an http request."""

    s = SoapMessage(
        endpoint="http://endpoint.example.com",
        method="getData",
        parameters=[("one", "1")],
        http_headers={"user-agent": "sonos"},
        soap_action="ACTION",
        soap_header="<a_header>data</a_header>",
        namespace="http://namespace.com",
        other_arg=4,
    )

    response = mock.MagicMock()
    response.headers = {}
    response.status_code = 200
    response.content = DUMMY_VALID_RESPONSE
    with mock.patch("requests.post", return_value=response) as fake_post:
        result = s.call()
        assert XML.tostring(result)
        fake_post.assert_called_once_with(
            "http://endpoint.example.com",
            headers={
                "SOAPACTION": '"ACTION"',
                "Content-Type": 'text/xml; charset="utf-8"',
                "user-agent": "sonos",
            },
            data=mock.ANY,
            other_arg=4,
        )
Beispiel #2
0
def test_call():
    """Calling a command should result in an http request."""

    s = SoapMessage(
        endpoint="http://endpoint.example.com",
        method="getData",
        parameters=[("one", "1")],
        http_headers={"user-agent": "sonos"},
        soap_action="ACTION",
        soap_header="<a_header>data</a_header>",
        namespace="http://namespace.com",
        other_arg=4,
    )

    response = mock.MagicMock()
    response.headers = {}
    response.status_code = 200
    response.content = DUMMY_VALID_RESPONSE
    with mock.patch("requests.post", return_value=response) as fake_post:
        result = s.call()
        assert XML.tostring(result)
        fake_post.assert_called_once_with(
            "http://endpoint.example.com",
            headers={"SOAPACTION": '"ACTION"', "Content-Type": 'text/xml; charset="utf-8"', "user-agent": "sonos"},
            data=mock.ANY,
            other_arg=4,
        )
Beispiel #3
0
def test_call():
    """Calling a command should result in an http request."""

    s = SoapMessage(
        endpoint='http://endpoint.example.com',
        method='getData',
        parameters=[('one', '1')],
        http_headers={'user-agent': 'sonos'},
        soap_action='ACTION',
        soap_header="<a_header>data</a_header>",
        namespace="http://namespace.com",
        other_arg=4)

    response = mock.MagicMock()
    response.headers = {}
    response.status_code = 200
    response.content = DUMMY_VALID_RESPONSE
    with mock.patch('requests.post', return_value=response) as fake_post:
        result = s.call()
        assert XML.tostring(result)
        fake_post.assert_called_once_with(
            'http://endpoint.example.com',
            headers={'SOAPACTION': '"ACTION"',
                     'Content-Type': 'text/xml; charset="utf-8"', 'user-agent':
                         'sonos'},
            data=mock.ANY, other_arg=4)
Beispiel #4
0
    def call(self, method, args=None):
        http_headers = {
            'Accept-Encoding': 'gzip, deflate',
            'User-Agent': 'Linux UPnP/1.0 Sonos/26.99-12345'
        }

        message = SoapMessage(endpoint=self.endpoint,
                              method=method,
                              parameters=[] if args is None else args,
                              http_headers=http_headers,
                              soap_action="http://www.sonos.com/Services/1"
                              ".1#{0}".format(method),
                              soap_header=self.get_soap_header(),
                              namespace='http://www.sonos.com/Services/1.1',
                              timeout=self.timeout)

        try:
            result_elt = message.call()
        except SoapFault as exc:
            raise MusicServiceException(exc.faultstring, exc.faultcode)

        result = list(
            parse(XML.tostring(result_elt),
                  process_namespaces=True,
                  namespaces={
                      'http://www.sonos.com/Services/1.1': None
                  }).values())[0]

        return result if result is not None else {}
Beispiel #5
0
def test_call():
    """ Calling a command should result in an http request"""

    s = SoapMessage(
        endpoint='http://endpoint.example.com',
        method='getData',
        parameters=[('one', '1')],
        http_headers={'user-agent': 'sonos'},
        soap_action='ACTION',
        soap_header="<a_header>data</a_header>",
        namespace="http://namespace.com",
        other_arg=4)

    response = mock.MagicMock()
    response.headers = {}
    response.status_code = 200
    response.content = DUMMY_VALID_RESPONSE
    with mock.patch('requests.post', return_value=response) as fake_post:
        result = s.call()
        assert XML.tostring(result)
        fake_post.assert_called_once_with(
            'http://endpoint.example.com',
            headers={'SOAPACTION': '"ACTION"',
                     'Content-Type': 'text/xml; charset="utf-8"', 'user-agent':
                         'sonos'},
            data=mock.ANY, other_arg=4)
Beispiel #6
0
def test_prepare_soap_header():
    """Check that the SOAP header is correctly wrapped."""
    s = SoapMessage("endpoint", "method")
    h = s.prepare_soap_header("<a><b></b></a>")
    assert h == "<s:Header><a><b></b></a></s:Header>"
    s = SoapMessage("endpoint", "method", http_headers={"test1": "one", "test2": "two"})
    h = s.prepare_soap_header(None)
    assert h == ""
Beispiel #7
0
def test_prepare_soap_header():
    """ Check that the SOAP header is correctly wrapped """
    s = SoapMessage('endpoint', 'method')
    h = s.prepare_soap_header('<a><b></b></a>')
    assert h == "<s:Header><a><b></b></a></s:Header>"
    s = SoapMessage('endpoint', 'method', http_headers={
        'test1': 'one', 'test2': 'two'})
    h = s.prepare_soap_header(None)
    assert h == ''
Beispiel #8
0
def test_prepare_headers():
    """ Check http_headers are correctly prepared """
    s = SoapMessage('endpoint', 'method')
    h = s.prepare_headers({'test1': 'one', 'test2': 'two'}, None)
    assert h == {'Content-Type': 'text/xml; charset="utf-8"',
                 'test2': 'two', 'test1': 'one'}
    h = s.prepare_headers(http_headers={'test1': 'one', 'test2': 'two'},
                          soap_action='soapaction')
    assert h == {'Content-Type': 'text/xml; charset="utf-8"',
                 'test2': 'two', 'test1': 'one',
                 'SOAPACTION': '"soapaction"'}
Beispiel #9
0
def test_prepare_headers():
    """Check http_headers are correctly prepared."""
    s = SoapMessage('endpoint', 'method')
    h = s.prepare_headers({'test1': 'one', 'test2': 'two'}, None)
    assert h == {'Content-Type': 'text/xml; charset="utf-8"',
                 'test2': 'two', 'test1': 'one'}
    h = s.prepare_headers(http_headers={'test1': 'one', 'test2': 'two'},
                          soap_action='soapaction')
    assert h == {'Content-Type': 'text/xml; charset="utf-8"',
                 'test2': 'two', 'test1': 'one',
                 'SOAPACTION': '"soapaction"'}
Beispiel #10
0
def test_prepare_headers():
    """Check http_headers are correctly prepared."""
    s = SoapMessage("endpoint", "method")
    h = s.prepare_headers({"test1": "one", "test2": "two"}, None)
    assert h == {"Content-Type": 'text/xml; charset="utf-8"', "test2": "two", "test1": "one"}
    h = s.prepare_headers(http_headers={"test1": "one", "test2": "two"}, soap_action="soapaction")
    assert h == {
        "Content-Type": 'text/xml; charset="utf-8"',
        "test2": "two",
        "test1": "one",
        "SOAPACTION": '"soapaction"',
    }
Beispiel #11
0
def test_prepare_soap_body():
    """Check that the SOAP body is correctly prepared."""
    # No params
    s = SoapMessage("endpoint", "method")
    b = s.prepare_soap_body("a_method", [], None)
    assert b == "<a_method></a_method>"
    # One param
    b = s.prepare_soap_body("a_method", [("one", "1")], None)
    assert b == "<a_method><one>1</one></a_method>"
    # Two params
    b = s.prepare_soap_body("a_method", [("one", "1"), ("two", "2")], None)
    assert b == "<a_method><one>1</one><two>2</two></a_method>"

    # And with a namespace

    b = s.prepare_soap_body("a_method", [("one", "1"), ("two", "2")], "http://a_namespace")
    assert b == "<a_method " 'xmlns="http://a_namespace"><one>1</one><two>2</two' "></a_method>"
Beispiel #12
0
def test_prepare_headers():
    """Check http_headers are correctly prepared."""
    s = SoapMessage("endpoint", "method")
    h = s.prepare_headers({"test1": "one", "test2": "two"}, None)
    assert h == {
        "Content-Type": 'text/xml; charset="utf-8"',
        "test2": "two",
        "test1": "one",
    }
    h = s.prepare_headers(
        http_headers={"test1": "one", "test2": "two"}, soap_action="soapaction"
    )
    assert h == {
        "Content-Type": 'text/xml; charset="utf-8"',
        "test2": "two",
        "test1": "one",
        "SOAPACTION": '"soapaction"',
    }
Beispiel #13
0
def test_prepare():
    """Test preparation of whole SOAP message."""
    s = SoapMessage(
        endpoint='endpoint',
        method='getData',
        parameters=[('one', '1')],
        http_headers={'timeout': '3'},
        soap_action='ACTION',
        soap_header="<a_header>data</a_header>",
        namespace="http://namespace.com")
    headers, data = s.prepare()
    assert data == '<?xml version="1.0"?><s:Envelope ' \
                   'xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" ' \
                   's:encodingStyle="http://schemas.xmlsoap.org/soap' \
                   '/encoding/"><s:Header><a_header>data</a_header></s' \
                   ':Header><s:Body><getData ' \
                   'xmlns="http://namespace.com"><one>1</one></getData></s' \
                   ':Body></s:Envelope>'
Beispiel #14
0
def test_prepare():
    """Test preparation of whole SOAP message."""
    s = SoapMessage(
        endpoint="endpoint",
        method="getData",
        parameters=[("one", "1")],
        http_headers={"timeout": "3"},
        soap_action="ACTION",
        soap_header="<a_header>data</a_header>",
        namespace="http://namespace.com",
    )
    headers, data = s.prepare()
    assert (data == '<?xml version="1.0"?><s:Envelope '
            'xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" '
            's:encodingStyle="http://schemas.xmlsoap.org/soap'
            '/encoding/"><s:Header><a_header>data</a_header></s'
            ":Header><s:Body><getData "
            'xmlns="http://namespace.com"><one>1</one></getData></s'
            ":Body></s:Envelope>")
Beispiel #15
0
def test_init():
    """Tests for initialisation of classes."""
    s = SoapMessage("http://endpoint_url", "a_method")
    assert s.endpoint == "http://endpoint_url"
    assert s.method == "a_method"
    assert s.parameters == []
    assert s.soap_action is None
    assert s.http_headers is None
    assert s.soap_header is None
    assert s.namespace is None
    assert s.request_args == {}
Beispiel #16
0
def test_prepare():
    """Test preparation of whole SOAP message."""
    s = SoapMessage(
        endpoint="endpoint",
        method="getData",
        parameters=[("one", "1")],
        http_headers={"timeout": "3"},
        soap_action="ACTION",
        soap_header="<a_header>data</a_header>",
        namespace="http://namespace.com",
    )
    headers, data = s.prepare()
    assert (
        data == '<?xml version="1.0"?><s:Envelope '
        'xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" '
        's:encodingStyle="http://schemas.xmlsoap.org/soap'
        '/encoding/"><s:Header><a_header>data</a_header></s'
        ":Header><s:Body><getData "
        'xmlns="http://namespace.com"><one>1</one></getData></s'
        ":Body></s:Envelope>"
    )
Beispiel #17
0
def test_prepare_soap_body():
    """ Check that the SOAP body is correctly prepared """
    # No params
    s = SoapMessage('endpoint', 'method')
    b = s.prepare_soap_body('a_method', [], None)
    assert b == "<a_method></a_method>"
    # One param
    b = s.prepare_soap_body('a_method', [('one', '1')], None)
    assert b == "<a_method><one>1</one></a_method>"
    # Two params
    b = s.prepare_soap_body('a_method', [
        ('one', '1'), ('two', '2')
    ], None)
    assert b == "<a_method><one>1</one><two>2</two></a_method>"

    # And with a namespace

    b = s.prepare_soap_body('a_method', [('one', '1'),
                                         ('two', '2')], "http://a_namespace")
    assert b == "<a_method " \
                'xmlns="http://a_namespace"><one>1</one><two>2</two' \
                '></a_method>'
Beispiel #18
0
def test_prepare_soap_header():
    """Check that the SOAP header is correctly wrapped."""
    s = SoapMessage("endpoint", "method")
    h = s.prepare_soap_header("<a><b></b></a>")
    assert h == "<s:Header><a><b></b></a></s:Header>"
    s = SoapMessage("endpoint", "method", http_headers={"test1": "one", "test2": "two"})
    h = s.prepare_soap_header(None)
    assert h == ""
Beispiel #19
0
def test_prepare_soap_header():
    """Check that the SOAP header is correctly wrapped."""
    s = SoapMessage('endpoint', 'method')
    h = s.prepare_soap_header('<a><b></b></a>')
    assert h == "<s:Header><a><b></b></a></s:Header>"
    s = SoapMessage('endpoint', 'method', http_headers={
        'test1': 'one', 'test2': 'two'})
    h = s.prepare_soap_header(None)
    assert h == ''
Beispiel #20
0
def test_prepare_soap_body():
    """Check that the SOAP body is correctly prepared."""
    # No params
    s = SoapMessage("endpoint", "method")
    b = s.prepare_soap_body("a_method", [], None)
    assert b == "<a_method></a_method>"
    # One param
    b = s.prepare_soap_body("a_method", [("one", "1")], None)
    assert b == "<a_method><one>1</one></a_method>"
    # Two params
    b = s.prepare_soap_body("a_method", [("one", "1"), ("two", "2")], None)
    assert b == "<a_method><one>1</one><two>2</two></a_method>"

    # And with a namespace

    b = s.prepare_soap_body("a_method", [("one", "1"), ("two", "2")],
                            "http://a_namespace")
    assert (b == "<a_method "
            'xmlns="http://a_namespace"><one>1</one><two>2</two'
            "></a_method>")
Beispiel #21
0
def test_prepare_soap_body():
    """Check that the SOAP body is correctly prepared."""
    # No params
    s = SoapMessage('endpoint', 'method')
    b = s.prepare_soap_body('a_method', [], None)
    assert b == "<a_method></a_method>"
    # One param
    b = s.prepare_soap_body('a_method', [('one', '1')], None)
    assert b == "<a_method><one>1</one></a_method>"
    # Two params
    b = s.prepare_soap_body('a_method', [
        ('one', '1'), ('two', '2')
    ], None)
    assert b == "<a_method><one>1</one><two>2</two></a_method>"

    # And with a namespace

    b = s.prepare_soap_body('a_method', [('one', '1'),
                                         ('two', '2')], "http://a_namespace")
    assert b == "<a_method " \
                'xmlns="http://a_namespace"><one>1</one><two>2</two' \
                '></a_method>'
Beispiel #22
0
    def call(self, method, args=None):
        """ Call a method on the server

        Args:
            method (str): The name of the method to call.
             args (list): A list of (parameter, value) pairs representing
                 the parameters of the method. Default None.

        Returns:
            (OrderedDict): An OrderedDict representing the response

        Raises:
            MusicServiceException

        """
        message = SoapMessage(endpoint=self.endpoint,
                              method=method,
                              parameters=[] if args is None else args,
                              http_headers=self.http_headers,
                              soap_action="http://www.sonos.com/Services/1"
                              ".1#{0}".format(method),
                              soap_header=self.get_soap_header(),
                              namespace=self.namespace,
                              timeout=self.timeout)

        try:
            result_elt = message.call()
        except SoapFault as exc:
            if 'Client.TokenRefreshRequired' in exc.faultcode:
                log.debug('Token refresh required. Trying again')
                # Remove any cached value for the SOAP header
                self._cached_soap_header = None

                # <detail>
                #   <refreshAuthTokenResult>
                #       <authToken>xxxxxxx</authToken>
                #       <privateKey>zzzzzz</privateKey>
                #   </refreshAuthTokenResult>
                # </detail>
                auth_token = exc.detail.findtext('.//authToken')
                private_key = exc.detail.findtext('.//privateKey')
                # We have new details - update the account
                self.music_service.account.oa_device_id = auth_token
                self.music_service.account.key = private_key
                message = SoapMessage(
                    endpoint=self.endpoint,
                    method=method,
                    parameters=args,
                    http_headers=self.http_headers,
                    soap_action="http://www.sonos.com/Services/1"
                    ".1#{0}".format(method),
                    soap_header=self.get_soap_header(),
                    namespace=self.namespace,
                    timeout=self.timeout)
                result_elt = message.call()

            else:
                raise MusicServiceException(exc.faultstring, exc.faultcode)

        # The top key in the OrderedDict will be the methodResult. Its
        # value may be None if no results were returned.
        result = parse(XML.tostring(result_elt),
                       process_namespaces=True,
                       namespaces={
                           'http://www.sonos.com/Services/1.1': None
                       }).values()[0]

        return result if result is not None else {}
Beispiel #23
0
    def call(self, method, args=None):
        """ Call a method on the server

        Args:
            method (str): The name of the method to call.
             args (list): A list of (parameter, value) pairs representing
                 the parameters of the method. Default None.

        Returns:
            (OrderedDict): An OrderedDict representing the response

        Raises:
            MusicServiceException

        """
        message = SoapMessage(
            endpoint=self.endpoint,
            method=method,
            parameters=[] if args is None else args,
            http_headers=self.http_headers,
            soap_action="http://www.sonos.com/Services/1"
                        ".1#{0}".format(method),
            soap_header=self.get_soap_header(),
            namespace=self.namespace,
            timeout=self.timeout)

        try:
            result_elt = message.call()
        except SoapFault as exc:
            if 'Client.TokenRefreshRequired' in exc.faultcode:
                log.debug('Token refresh required. Trying again')
                # Remove any cached value for the SOAP header
                self._cached_soap_header = None

                # <detail>
                #   <refreshAuthTokenResult>
                #       <authToken>xxxxxxx</authToken>
                #       <privateKey>zzzzzz</privateKey>
                #   </refreshAuthTokenResult>
                # </detail>
                auth_token = exc.detail.findtext('.//authToken')
                private_key = exc.detail.findtext('.//privateKey')
                # We have new details - update the account
                self.music_service.account.oa_device_id = auth_token
                self.music_service.account.key = private_key
                message = SoapMessage(
                    endpoint=self.endpoint,
                    method=method,
                    parameters=args,
                    http_headers=self.http_headers,
                    soap_action="http://www.sonos.com/Services/1"
                                ".1#{0}".format(method),
                    soap_header=self.get_soap_header(),
                    namespace=self.namespace,
                    timeout=self.timeout)
                result_elt = message.call()

            else:
                raise MusicServiceException(exc.faultstring, exc.faultcode)

        # The top key in the OrderedDict will be the methodResult. Its
        # value may be None if no results were returned.
        result = parse(
            XML.tostring(result_elt), process_namespaces=True,
            namespaces={'http://www.sonos.com/Services/1.1': None}
        ).values()[0]

        return result if result is not None else {}