Search code examples
djangopython-requestsdjango-testing

Using requests module with Django APITestCase and APIClient?


I'm trying to test my command line client with Django. I want to use the requests module in my client to fetch data from Django, but I'm testing this inside an APITestCase class so I can create factories using Factory_Boy.

I get a connection refused error.

The file in my front-end to call the view:

from . import urls
import requests, json
HEADERS = {'content-type':'application/json'}
BASE_URL = 'http://127.0.0.1:80/'

def post(url, **data):
    query = json.dumps(data)
    r = requests.post(BASE_URL+url, data=query, headers=HEADERS)
    return r.json()


def get(url, **data):
    query = json.dumps(data)
    r = requests.get(BASE_URL+url, data=query, headers=HEADERS)
    return r.json()

The tests file for Django app, inside a APITestCase class:

def setUp(self):
    self.client = APIClient()
    self.populate_addresses()
    self.populate_carriers()
    self.populate_drivers()



def test_requests(self):
    a = query.query_address(err_msg='Stop not found.',
                            conf_msg='Create new stop.')
    

    



def populate_addresses(self):
    self.Address__A1 = factories.AddressFactory(
                    name='BDI', 
                    city='CHATSWORTH',
                    zip_code='92111', 
                    state='CA',
                    street='12345 BANDINI BLVD')
    self.Address__A2 = factories.AddressFactory(
                    name='BM', 
                    city='FAIRFIELD',
                    zip_code='92111', 
                    state='CA',
                    street='2400 HUNTINGTON BLVD')

Solution

  • APITestCase has already APIClient module. You can access it with self.client and you can send request like self.client.post(#url,#data) inside your test methods. You can get more detail about APIClient here