Beispiel #1
0
def search(query: str,
           start: int=0,
           limit: int=10,
           sortby: t.List[t.Tuple[str, str]]=None,
           filter_fields: t.Dict[str, str]=None,
           filter_queries: t.Dict[str, str]=None,
           show: t.List[str]=None,
           hide: t.List[str]=None,
           **kwargs
           ) -> models.PartsSearchResult:
    """
    Search Octopart for a general keyword (and optional filters).

    Args:
        query (str): Free-form keyword query

    Kwargs:
        start: Ordinal position of first result
        limit: Maximum number of results to return
        sortby: [(fieldname, order)] list of tuples
        filter_fields: {fieldname: value} dict
        filter_queries: {fieldname: value} dict
        include_*, e.g. include_cad_models (bool): by setting to True, the
            corresponding field is set in the include directive of the
            Octopart API call, resulting in optional information being
            returned (see enum `INCLUDES` for list of possible argument
            names)

    Returns:
        list of `models.PartsSearchResult` objects.
    """
    # assemble include[] directives as per
    # https://octopart.com/api/docs/v3/rest-api#include-directives
    includes = include_directives_from_kwargs(**kwargs)

    client = OctopartClient()
    response = client.search(
        query,
        start=start,
        limit=limit,
        sortby=sortby,
        filter_fields=filter_fields,
        filter_queries=filter_queries,
        includes=includes,
        show=show,
        hide=hide,
    )
    return models.PartsSearchResult(response)
Beispiel #2
0
 def test_malformed_search_query(self):
     client = OctopartClient(api_key='TEST_TOKEN')
     with pytest.raises(OctopartError):
         client.search(["query1", "query2"])
Beispiel #3
0
class PartSearchTests(TestCase):
    """Tests for the client's search() method"""
    def setUp(self):
        self.client = OctopartClient(api_key='TEST_TOKEN')

    @patch('requests.get')
    def test_malformed_match_query(self, mock_get):
        with pytest.raises(OctopartError):
            self.client.search([{'query': ["not", "a", "string"]}])
        # the exception should prevent any queries from being made
        assert not mock_get.called

    def test_hide_directive(self):
        response_body = {
            "__class__":
            "SearchResponse",
            "results": [{
                "__class__": "SearchResult",
                "item": {
                    "__class__": "Part",
                    "brand": {
                        "__class__": "Brand",
                        "homepage_url": "http://www.ohmite.com/",
                        "name": "Ohmite",
                        "uid": "574996437b3e808e"
                    },
                    "manufacturer": {
                        "__class__": "Manufacturer",
                        "homepage_url": "http://www.ohmite.com/",
                        "name": "Ohmite",
                        "uid": "5da998a375de8e6e"
                    },
                    "mpn": "D25K10KE",
                    "octopart_url":
                    "https://octopart.com/d25k10ke-ohmite-150892",  # noqa
                    "redirected_uids": [],
                    "uid": "3cc3f5cb54c9e304"
                },
            }]
        }

        with octopart_mock_response(response_body) as response:
            dict_ = self.client.search(query='resistor 10kohm 10%',
                                       hide=['offers'])
            [result] = dict_['results']
            assert result['item']['mpn'] == "D25K10KE"
            called_url = request_url_from_request_mock(response)
            assert '/parts/search' in called_url
            assert 'hide%5B%5D=offers' in called_url

    def test_show_directive(self):
        response_body = {
            "__class__":
            "SearchResponse",
            "results": [{
                "__class__": "SearchResult",
                "item": {
                    "offers": [{
                        "__class__": "PartOffer",
                        "eligible_region": "US",
                        "factory_lead_days": None,
                        "factory_order_multiple": None,
                        "in_stock_quantity": 29,
                        "is_authorized": True,
                        "is_realtime": False,
                        "last_updated": "2018-04-30T17:53:11Z",
                        "moq": 1,
                        "multipack_quantity": "1",
                        "octopart_rfq_url": None,
                        "on_order_eta": None,
                        "on_order_quantity": None,
                        "order_multiple": None,
                        "packaging": None,
                        "prices": {
                            "USD": [[1, "13.65000"], [10, "12.40000"],
                                    [25, "11.17000"], [50, "10.56000"],
                                    [100, "10.44000"], [250, "8.92000"],
                                    [500, "8.75000"]]
                        },
                        "product_url":
                        "https://octopart.com/click/track?ak=a8cfd5a0&sig=08c4b0d&sid=2402&ppid=150892&vpid=3009946&ct=offers",  # noqa
                        "seller": {
                            "__class__": "Seller",
                            "display_flag": "US",
                            "has_ecommerce": True,
                            "homepage_url": "http://www.newark.com",
                            "id": "2402",
                            "name": "Newark",
                            "uid": "d294179ef2900153"
                        },
                        "sku": "64K4273"
                    }]
                }
            }]
        }

        with octopart_mock_response(response_body) as response:
            dict_ = self.client.search(query='resistor 10kohm 10%',
                                       show=['offers'])
            [result] = dict_['results']
            [offer] = result['item']['offers']
            assert offer['in_stock_quantity'] == 29
            called_url = request_url_from_request_mock(response)
            assert '/parts/search' in called_url
            assert 'show%5B%5D=offers' in called_url

    def test_include_directive(self):
        with octopart_mock_response() as response:
            self.client.search(query='resistor 10kohm 10%',
                               includes=['cad_models'])
            called_url = request_url_from_request_mock(response)
            assert '/parts/search' in called_url
            assert 'include%5B%5D=cad_models' in called_url

    def test_no_directives(self):
        with octopart_mock_response() as response:
            self.client.search(query='resistor 10kohm 10%')
            called_url = request_url_from_request_mock(response)
            assert '/parts/search' in called_url
            assert 'hide%5B%5D=' not in called_url
            assert 'show%5B%5D=' not in called_url
            assert 'include%5B%5D=' not in called_url

    def test_complete_example(self):
        with octopart_mock_response() as response:
            self.client.search(
                query='resistor 10kohm 10%',
                show=['brand.name'],
                includes=['imagesets'],
                start=50,
                limit=50,
                sortby=[('score', 'desc')],
            )
            called_url = request_url_from_request_mock(response)
            assert 'q=resistor+10kohm+10%25' in called_url
            assert 'sortby=score+desc' in called_url
            assert 'start=50' in called_url
            assert 'limit=50' in called_url
            assert 'show%5B%5D=brand.name' in called_url  # %5B%5D is []
            assert 'include%5B%5D=imagesets' in called_url