metagenedb.py 2.65 KB
Newer Older
1
2
from requests.exceptions import HTTPError

3
from bioapi import MetageneDBCatalogGeneAPI
4
5
6
7
8
9
10
11
12
13
14
from django.urls import reverse


class MetageneDBAPIMock(MetageneDBCatalogGeneAPI):
    """
    Just a simple mock to go through the Test client. The idea is to test the upsert behaviour and not
    the insertion to the db.
    """
    KEY_ID = ''
    BASE_REVERSE = 'api'
    REVERSE_PATH = ''
15
    BAD_REQUESTS = range(400, 452)
16
17
18
19
20
21

    def __init__(self, client):
        self.client = client
        self.reverse_path = ':'.join([self.BASE_REVERSE, self.REVERSE_PATH])

    def get_all(self, params=None):
22
23
24
25
26
27
28
29
        response = self.client.get(reverse(f'{self.reverse_path}-list'), params)
        if response.status_code in self.BAD_REQUESTS:
            raise HTTPError
        return response.json()

    def get(self, entry_id, params=None):
        response = self.client.get(reverse(f'{self.reverse_path}-detail', kwargs={self.KEY_ID: entry_id}), params)
        if response.status_code in self.BAD_REQUESTS:
30
31
32
33
34
            raise HTTPError
        return response.json()

    def post(self, data):
        response = self.client.post(reverse(f'{self.reverse_path}-list'), data, format='json')
35
        if response.status_code in self.BAD_REQUESTS:
36
37
38
            raise HTTPError
        return response.json()

39
40
41
42
43
    def put(self, data, entry_id=None):
        if entry_id:
            return self.client.put(reverse(f'{self.reverse_path}-detail', kwargs={self.KEY_ID: entry_id}),
                                   data, format='json').json()
        return self.client.put(reverse(f'{self.reverse_path}-list'), data, format='json').json()
44
45
46
47
48
49


class MetageneDBCatalogGeneAPIMock(MetageneDBAPIMock):
    KEY_ID = 'gene_id'
    REVERSE_PATH = 'catalog:v1:genes'

50
51
52
53
54
    def get_gene_length(self, params=None):
        reverse_path = f"{self.reverse_path}-gene-length"
        response = self.client.get(reverse(reverse_path), params)
        if response.status_code in self.BAD_REQUESTS:
            raise HTTPError
55
56
        if response.status_code == 204:  # no content
            return {}
57
58
        return response.json()

59
60
61
62
63
64
65
66
67
    def get_tax_counts(self, params=None):
        reverse_path = f"{self.reverse_path}-taxonomy-counts"
        response = self.client.get(reverse(reverse_path), params)
        if response.status_code in self.BAD_REQUESTS:
            raise HTTPError
        if response.status_code == 204:  # no content
            return {}
        return response.json()

68
69
70
71

class MetageneDBCatalogTaxonomyAPIMock(MetageneDBAPIMock):
    KEY_ID = 'gene_id'
    REVERSE_PATH = 'catalog:v1:taxonomy'
72
73
74
75
76


class MetageneDBCatalogFunctionAPIMock(MetageneDBAPIMock):
    KEY_ID = 'function_id'
    REVERSE_PATH = 'catalog:v1:functions'