Example #1
0
 def test_error_handlers(self):
     self.assertTrue(urls.handler404.endswith('.handler404'))
     factory = RequestFactory()
     request = factory.get('/')
     response = handler404(request)
     self.assertEqual(response.status_code, 404)
     self.assertIn('404 Not Found!!', unicode(response))
Example #2
0
File: tests.py Project: 400yk/Ejub
    def test_email_address_created(self):
        factory = RequestFactory()
        request = factory.get('/accounts/login/callback/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        MessageMiddleware().process_request(request)

        User = get_user_model()
        user = User()
        setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'test')
        setattr(user, account_settings.USER_MODEL_EMAIL_FIELD, 'test@test.com')

        account = SocialAccount(user=user, provider='openid', uid='123')
        sociallogin = SocialLogin(account)
        complete_social_login(request, sociallogin)

        user = User.objects.get(
            **{account_settings.USER_MODEL_USERNAME_FIELD: 'test'}
        )
        self.assertTrue(
            SocialAccount.objects.filter(user=user, uid=account.uid).exists()
        )
        self.assertTrue(
            EmailAddress.objects.filter(user=user, email=user_email(user)).exists()
        )
    def test_redirect_to_the_app_detail_page(self, get):
        data = {
            "name": "app1",
            "units": [
                {"Ip": "10.10.10.10"},
                {"Ip": "9.9.9.9"},
            ],
        }
        response_mock = Mock(status_code=200)
        response_mock.json.return_value = data
        get.return_value = response_mock

        data = {"units": '2'}
        request = RequestFactory().post("/", data)
        request.session = {"tsuru_token": "admin"}

        response = ChangeUnit.as_view()(request, app_name="app_name")

        self.assertEqual(302, response.status_code)
        self.assertEqual("/apps/app_name/", response.items()[1][1])

        get.assert_called_with(
            '{}/apps/app_name'.format(settings.TSURU_HOST),
            headers={'authorization': 'admin'}
        )
Example #4
0
class CsrfTokenTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.view = views.CsrfToken()

    def test_lazy_token_called(self):
        """
        If the csrf_token variable in the RequestContext is a lazy
        callable, make sure it is called during the view.
        """
        global _lazy_csrf_token_called
        _lazy_csrf_token_called = False

        # I'd love to use a Mock here instead, but lazy doesn't behave
        # well with Mocks for some reason.
        def _lazy_csrf_token():
            global _lazy_csrf_token_called
            _lazy_csrf_token_called = True
            return 'asdf'
        csrf_token = lazy(_lazy_csrf_token, six.text_type)()

        request = self.factory.get('/browserid/csrf/')
        with patch('django_browserid.views.RequestContext') as RequestContext:
            RequestContext.return_value = {'csrf_token': csrf_token}
            response = self.view.get(request)

        eq_(response.status_code, 200)
        eq_(response.content, b'asdf')
        ok_(_lazy_csrf_token_called)

    def test_never_cache(self):
        request = self.factory.get('/browserid/csrf/')
        response = self.view.get(request)
        eq_(response['Cache-Control'], 'max-age=0')
Example #5
0
    def test_send_mail(self, fake_messages):
        """Test EmailRepsForm email sending functionality."""

        data = {"subject": "Test email subject", "body": "Test email body", "functional_area": self.functional_area.id}

        form = EmailRepsForm(data=data)
        ok_(form.is_valid())

        area = self.functional_area
        UserFactory.create_batch(20, userprofile__functional_areas=[area])

        factory = RequestFactory()
        request = factory.request()
        request.user = UserFactory.create()

        reps = User.objects.filter(userprofile__functional_areas__name=area)

        form.send_email(request, reps)

        eq_(len(mail.outbox), 20)

        address = lambda u: "%s %s <%s>" % (u.first_name, u.last_name, u.email)
        recipients = map(address, reps)

        receivers = []
        for i in range(0, len(mail.outbox)):
            eq_(mail.outbox[i].subject, data["subject"])
            eq_(mail.outbox[i].body, data["body"])
            receivers.append(mail.outbox[i].to[0])

        eq_(set(receivers), set(recipients))
        fake_messages.assert_called_with(ANY, "Email sent successfully.")
Example #6
0
 def test_should_use_detail_template(self):
     request = RequestFactory().get("/")
     request.session = {"tsuru_token":"admin"}
     with mock.patch("requests.get") as get:
         get.return_value = mock.Mock(status_code=200, json={})
         response = AppDetail.as_view()(request, app_name="app1")
     self.assertEqual("apps/details.html", response.template_name)
Example #7
0
    def call_view(
            self,
            view_name,
            mock_request,
            user=None,
            post_params=None,
            view_args=None
    ):
        self._set_mock_request_data(
            mock_request,
            {
                "user_id": str(self.student.id),
                "group_id": self.student_cohort.id,
                "closed": False,
                "type": "thread"
            }
        )
        mock_request.return_value.status_code = 200
        request = RequestFactory().post("dummy_url", post_params or {})
        request.user = user or self.student
        request.view_name = view_name

        return getattr(views, view_name)(
            request,
            course_id=self.course.id.to_deprecated_string(),
            thread_id="dummy",
            **(view_args or {})
        )
Example #8
0
 def testGetSubdomainMiddleware5(self):
     "Test GetSubdomainMiddleware.process_request populates the variables we need correctly"
     rf = RequestFactory(domain = 'boox.notfoo.tld')
     request = rf.request()
     middleware = GetSubdomainMiddleware()
     middleware.process_request(request)
     self.assertEqual(request.META['domain'], 'boox.notfoo.tld')
    def test_toc_toy_from_section(self):
        chapter = 'Overview'
        chapter_url = '%s/%s/%s' % ('/courses', self.course_name, chapter)
        section = 'Welcome'
        factory = RequestFactory()
        request = factory.get(chapter_url)
        field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
            self.toy_course.id, self.portal_user, self.toy_course, depth=2)

        expected = ([{'active': True, 'sections':
                      [{'url_name': 'Toy_Videos', 'display_name': u'Toy Videos', 'graded': True,
                        'format': u'Lecture Sequence', 'due': None, 'active': False},
                       {'url_name': 'Welcome', 'display_name': u'Welcome', 'graded': True,
                        'format': '', 'due': None, 'active': True},
                       {'url_name': 'video_123456789012', 'display_name': 'Test Video', 'graded': True,
                        'format': '', 'due': None, 'active': False},
                       {'url_name': 'video_4f66f493ac8f', 'display_name': 'Video', 'graded': True,
                        'format': '', 'due': None, 'active': False}],
                      'url_name': 'Overview', 'display_name': u'Overview'},
                     {'active': False, 'sections':
                      [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True,
                        'format': '', 'due': None, 'active': False}],
                      'url_name': 'secret:magic', 'display_name': 'secret:magic'}])

        actual = render.toc_for_course(self.portal_user, request, self.toy_course, chapter, section, field_data_cache)
        for toc_section in expected:
            self.assertIn(toc_section, actual)
Example #10
0
 def test_returns_valid_view(self):
     rf = RequestFactory()
     request = rf.get('/page-1/')
     request.user = AnonymousUser()
     response = page_dispatch(request)
     self.assertEqual(200, response.status_code)
     self.assertIsInstance(response, TemplateResponse)
Example #11
0
    def test_serialize_object_with_cache_copy(self):
        """Testing WebAPIResource.serialize_object always returns a copy of
        the cached data
        """
        class TestObject(object):
            my_field = 'abc'

        request = RequestFactory().request()
        request.user = User()

        resource = WebAPIResource()
        resource.fields = {
            'my_field': {
                'type': six.text_type,
            }
        }

        obj = TestObject()

        # We check this three times, since prior to Djblets 2.0.20, we would
        # first return a copy of the newly-generated data, then the cached
        # copy of the original data, and then the cached copy again (which
        # would no longer be untouched).
        data = resource.serialize_object(obj, request=request)
        self.assertIn('my_field', data)
        del data['my_field']

        data = resource.serialize_object(obj, request=request)
        self.assertIn('my_field', data)
        del data['my_field']

        data = resource.serialize_object(obj, request=request)
        self.assertIn('my_field', data)
class LoginViewTestCase(unittest.TestCase):
    
    def setUp(self):
        self.factory = RequestFactory()
    
    def test_get(self):
        request = self.factory.get(reverse("account_login"))
        request.user = AnonymousUser()
        response = LoginView.as_view()(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.template_name, ["account/login.html"])

    def test_get_disabled(self):
        request = self.factory.get(reverse("account_login"))
        request.user = AnonymousUser()
        response = LoginDisabledView.as_view()(request)
        self.assertEqual(response.status_code, 200)
    
    def test_post_disabled(self):
        request = self.factory.post(reverse("account_login"))
        request.user = AnonymousUser()
        response = LoginDisabledView.as_view()(request)
        self.assertEqual(response.status_code, 403)
    
    def test_custom_redirect_field(self):
        request = self.factory.request()
        request.GET = {"next_page": "/profile/"}
        form = LoginUsernameForm({"username": "test", "password": "password"})
        view = LoginRedirectView(request=request, redirect_field_name="next_page")
        self.assertEqual("/profile/", view.form_valid(form)["Location"])
Example #13
0
    def __init__(self, request=None):
        # MakoMiddleware Note:
        # Line below has the side-effect of writing to a module level lookup
        # table that will allow problems to render themselves. If this is not
        # present, problems that a student hasn't seen will error when loading,
        # causing the grading system to under-count the possible score and
        # inflate their grade. This dependency is bad and was probably recently
        # introduced. This is the bandage until we can trace the root cause.
        m = MakoMiddleware()

        # Get basic auth (username/password) for
        # xqueue connection if it's in the settings

        if settings.XQUEUE_INTERFACE.get('basic_auth') is not None:
            requests_auth = HTTPBasicAuth(
                    *settings.XQUEUE_INTERFACE['basic_auth'])
        else:
            requests_auth = None

        if request is None:
            factory = RequestFactory()
            self.request = factory.get('/')
        else:
            self.request = request

        self.xqueue_interface = XQueueInterface(
                settings.XQUEUE_INTERFACE['url'],
                settings.XQUEUE_INTERFACE['django_auth'],
                requests_auth,
                )
        self.whitelist = CertificateWhitelist.objects.all()
        self.restricted = UserProfile.objects.filter(allow_certificate=False)
Example #14
0
    def test_context_processor(self):
        """ Test wishlist_items context processor. """

        # Create one item for testing
        item = G(WishlistItem)

        # Request factory and request
        factory = RequestFactory()
        request = factory.get('/')

        # Anonymous user
        request.user = AnonymousUser()

        # No context for anonymous users
        result = wishlist_items(request)
        self.assertEquals(result, {})

        # User set, should return items for user
        request.user = item.user
        result = wishlist_items(request)

        self.assertEquals(len(result['wishlist_items']), 1)

        self.assertEquals(
            result['wishlist_items'][0],
            WishlistItem.objects.for_user(user=item.user)[0]
        )
 def test_should_redirect_to_login_page_if_user_is_not_authenticated(self):
     request = RequestFactory().get('/')
     request.session = {}
     response = StubView.as_view()(request)
     self.assertIsInstance(response, HttpResponseRedirect)
     expected_url = "%s?next=%s" % (reverse('login'), request.path)
     self.assertEqual(expected_url, response['Location'])
Example #16
0
 def _verify_cohort_settings_response(self, expected_response):
     """ Verify that the response was successful and matches the expected JSON payload. """
     request = RequestFactory().get("dummy_url")
     request.user = AdminFactory()
     response = cohorting_settings(request, unicode(self.course.id))
     self.assertEqual(200, response.status_code)
     self.assertEqual(expected_response, json.loads(response.content))
    def create_get_request(user, path):
        rf = RequestFactory()
        get_request = rf.get(path)
        get_request.user = user
        get_request.session = dict()

        return get_request
Example #18
0
    def test_valid_key(self):
        """Make sure the key is valid"""
        actual_ip_plus_desc = actual_ip_plus_context(
            lambda req: req.POST.get('description', 'no description')
        )

        url = reverse('feedback')
        factory = RequestFactory(HTTP_X_CLUSTER_CLIENT_IP='192.168.100.101')

        # create a request with this as the description
        desc = u'\u5347\u7ea7\u4e86\u65b0\u7248\u672c\u4e4b\u540e' * 16
        req = factory.post(url, {
            'description': desc
        })
        key = actual_ip_plus_desc(req)

        # Key can't exceed memcached 250 character max
        length = len(key)
        assert length < 250

        # Key must be a string
        assert isinstance(key, str)

        # create a request with this as the description
        second_desc = u'\u62e9\u201c\u5728\u65b0\u6807\u7b7e\u9875\u4e2d' * 16
        second_req = factory.post(url, {
            'description': second_desc
        })
        second_key = actual_ip_plus_desc(second_req)

        # Two descriptions with the same ip address should produce
        # different keys.
        assert key != second_key
Example #19
0
    def __init__(self, request=None):

        # Get basic auth (username/password) for
        # xqueue connection if it's in the settings

        if settings.XQUEUE_INTERFACE.get('basic_auth') is not None:
            requests_auth = HTTPBasicAuth(
                *settings.XQUEUE_INTERFACE['basic_auth'])
        else:
            requests_auth = None

        if request is None:
            factory = RequestFactory()
            self.request = factory.get('/')
        else:
            self.request = request

        self.xqueue_interface = XQueueInterface(
            settings.XQUEUE_INTERFACE['url'],
            settings.XQUEUE_INTERFACE['django_auth'],
            requests_auth,
        )
        self.whitelist = CertificateWhitelist.objects.all()
        self.restricted = UserProfile.objects.filter(allow_certificate=False)
        self.use_https = True
Example #20
0
class GetNetTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.url = reverse('calendar:list')

    def test_valid_next(self):
        url = self.url + '?cal_next=1'
        req = self.factory.get(url)
        net = get_net(req)
        self.assertEqual(net, 1)

    def test_valid_prev(self):
        url = self.url + '?cal_prev=1'
        req = self.factory.get(url)
        net = get_net(req)
        self.assertEqual(net, -1)

    def test_invalid(self):
        url = self.url + '?cal_next=nann'
        req = self.factory.get(url)
        net = get_net(req)
        self.assertEqual(net, 0)

    def test_valid_next_and_prev(self):
        url = self.url + '?cal_next=1&cal_prev=2'
        req = self.factory.get(url)
        net = get_net(req)
        self.assertEqual(net, -1)
Example #21
0
class LogoutTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

        _get_next_patch = patch('django_browserid.views._get_next')
        self._get_next = _get_next_patch.start()
        self.addCleanup(_get_next_patch.stop)

    def test_redirect(self):
        """Include LOGOUT_REDIRECT_URL in the response."""
        request = self.factory.post('/')
        logout = views.Logout.as_view()
        self._get_next.return_value = None

        with patch.object(views.Logout, 'redirect_url', '/test/foo'):
            with patch('django_browserid.views.auth.logout') as auth_logout:
                response = logout(request)

        auth_logout.assert_called_with(request)
        eq_(response.status_code, 200)
        self.assert_json_equals(response.content, {'redirect': '/test/foo'})

    def test_redirect_next(self):
        """
        If _get_next returns a URL, use it for the redirect parameter.
        """
        request = self.factory.post('/')
        logout = views.Logout.as_view()
        self._get_next.return_value = '/test/bar'

        with patch.object(views.Logout, 'redirect_url', '/test/foo'):
            with patch('django_browserid.views.auth.logout'):
                response = logout(request)

        self.assert_json_equals(response.content, {'redirect': '/test/bar'})
Example #22
0
    def test_create_account(self):
        # Create a new account, which should have empty account settings by default.
        create_account(self.USERNAME, self.PASSWORD, self.EMAIL)

        # Retrieve the account settings
        user = User.objects.get(username=self.USERNAME)
        request = RequestFactory().get("/api/user/v1/accounts/")
        request.user = user
        account_settings = get_account_settings(request)

        # Expect a date joined field but remove it to simplify the following comparison
        self.assertIsNotNone(account_settings['date_joined'])
        del account_settings['date_joined']

        # Expect all the values to be defaulted
        self.assertEqual(account_settings, {
            'username': self.USERNAME,
            'email': self.EMAIL,
            'name': u'',
            'gender': None,
            'goals': None,
            'is_active': False,
            'level_of_education': None,
            'mailing_address': None,
            'year_of_birth': None,
            'country': None,
            'bio': None,
            'profile_image': {
                'has_image': False,
                'image_url_full': request.build_absolute_uri('/static/default_50.png'),
                'image_url_small': request.build_absolute_uri('/static/default_10.png'),
            },
            'requires_parental_consent': True,
            'language_proficiencies': [],
        })
Example #23
0
class GetNextTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_no_param(self):
        """If next isn't in the POST params, return None."""
        request = self.factory.post('/')
        eq_(views._get_next(request), None)

    def test_is_safe(self):
        """Return the value of next if it is considered safe."""
        request = self.factory.post('/', {'next': '/asdf'})
        request.get_host = lambda: 'myhost'

        with patch.object(views, 'is_safe_url', return_value=True) as is_safe_url:
            eq_(views._get_next(request), '/asdf')
            is_safe_url.assert_called_with('/asdf', host='myhost')

    def test_isnt_safe(self):
        """If next isn't safe, return None."""
        request = self.factory.post('/', {'next': '/asdf'})
        request.get_host = lambda: 'myhost'

        with patch.object(views, 'is_safe_url', return_value=False) as is_safe_url:
            eq_(views._get_next(request), None)
            is_safe_url.assert_called_with('/asdf', host='myhost')
Example #24
0
    def test_login_blocked_for_non_standard_login_views_with_msg(self):
        """
        Check that a view wich returns the expected status code and the
        expected message is causing the IP to be locked out.
        """
        @watch_login(status_code=401, msg='Invalid credentials')
        def fake_api_401_login_view_without_msg(request):
            """ Fake the api login with 401 """
            return HttpResponse('Sorry, Invalid credentials',
                                status=401)

        request_factory = RequestFactory()
        request = request_factory.post('api/login')
        request.user = AnonymousUser()
        request.session = SessionStore()

        request.META['HTTP_X_FORWARDED_FOR'] = '192.168.24.24'

        for _ in range(3):
            fake_api_401_login_view_without_msg(request)

            data_out = utils.get_blocked_ips()
            self.assertEqual(data_out, [])

        fake_api_401_login_view_without_msg(request)

        data_out = utils.get_blocked_ips()
        self.assertEqual(data_out, ['192.168.24.24'])
Example #25
0
class InValidStockRSRTestCase(TestCase):

    """Testing request to stock RSR.

    invalid hosts :
    - "invalid_host"
    - ""
    """

    def setUp(self):
        """Setup."""
        self.factory = RequestFactory()
        self.req_not_found_host = self.factory.get('/', {}, HTTP_HOST='not-found.akvo.org')
        self.req_not_found_host2 = self.factory.get('/', {}, HTTP_HOST='not-found.test.akvo.org')
        self.req_invalid_host = self.factory.get('/', {}, HTTP_HOST='invalid_host')
        self.req_empty_host = self.factory.get('/', {}, HTTP_HOST='')

    def test_is_rsr_host(self):
        """Test request to normal RSR host."""
        self.assertFalse(_is_rsr_host(self.req_not_found_host.get_host()))
        self.assertFalse(_is_rsr_host(self.req_not_found_host2.get_host()))
        with self.assertRaises(DisallowedHost):
            _is_rsr_host(self.req_invalid_host.get_host())
        with self.assertRaises(DisallowedHost):
            _is_rsr_host(self.req_empty_host.get_host())
Example #26
0
def dump_app(id, **kw):
    from mkt.webapps.serializers import AppSerializer
    # Because @robhudson told me to.
    # Note: not using storage because all these operations should be local.
    target_dir = os.path.join(settings.DUMPED_APPS_PATH, 'apps',
                              str(id / 1000))
    target_file = os.path.join(target_dir, str(id) + '.json')

    try:
        obj = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        task_log.info(u'Webapp does not exist: {0}'.format(id))
        return

    req = RequestFactory().get('/')
    req.user = AnonymousUser()
    req.REGION = RESTOFWORLD

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    task_log.info('Dumping app {0} to {1}'.format(id, target_file))
    res = AppSerializer(obj, context={'request': req}).data
    json.dump(res, open(target_file, 'w'), cls=JSONEncoder)
    return target_file
    def test_add_unit(self, put, get):
        data = {
            "name": "app1",
            "units": [
                {"Ip": "10.10.10.10"},
                {"Ip": "9.9.9.9"},
            ],
        }
        response_mock = Mock(status_code=200)
        response_mock.json.return_value = data
        get.return_value = response_mock

        data = {"units": '10'}
        request = RequestFactory().post("/", data)
        request.session = {"tsuru_token": "admin"}

        ChangeUnit.as_view()(request, app_name="app_name")

        put.assert_called_with(
            '{}/apps/app_name/units'.format(settings.TSURU_HOST),
            data='8',
            headers={'authorization': 'admin'}
        )

        get.assert_called_with(
            '{}/apps/app_name'.format(settings.TSURU_HOST),
            headers={'authorization': 'admin'}
        )
Example #28
0
    def test_new_user(self):
        """Tests that new users get redirected to new_user page"""
        # Create a user that has no profile--this is the sign that the
        # user is new!
        new_user = UserFactory(profile=None)
        self.client_login_user(new_user)

        # Now do some ridiculous setup so we can call login_success()
        # on the Verify and see if it did what it should be doing.

        # FIXME - this can go away post django-browserid 0.9
        new_user.backend = 'django_browserid.auth.BrowserIDBackend'

        post_request = RequestFactory().post(reverse('browserid.login'))
        post_request.user = new_user
        post_request.session = self.client.session

        fv = FjordVerify()
        fv.user = new_user
        fv.request = post_request

        resp = fv.login_success()
        eq_(200, resp.status_code)
        body = json.loads(resp.content)
        eq_(body['redirect'], reverse('new-user-view'))
Example #29
0
    def test_admin_timeline_prunes_user_output(self):
        """multiple users in timeline is confusing."""
        admin = self.User.objects.create(username="admin", email="admin@example.com")
        admin.is_staff = True
        admin.is_superuser = True
        admin.save()

        # create a drip campaign that will surely give us duplicates.
        model_drip = Drip.objects.create(
            name="A Custom Week Ago", subject_template="HELLO {{ user.username }}", body_html_template="KETTEHS ROCK!"
        )
        QuerySetRule.objects.create(
            drip=model_drip,
            field_name="date_joined",
            lookup_type="gte",
            field_value=(timezone.now() - timedelta(days=1)).isoformat(),
        )

        # then get it's admin view.
        rf = RequestFactory()
        timeline_url = reverse(
            "admin:drip_timeline", kwargs={"drip_id": model_drip.id, "into_past": 3, "into_future": 3}
        )

        request = rf.get(timeline_url)
        request.user = admin

        match = resolve(timeline_url)

        response = match.func(request, *match.args, **match.kwargs)

        # check that our admin (not excluded from test) is shown once.
        self.assertEqual(unicode(response.content).count(admin.email), 1)
    def test_callback_with_permissions(self, post_mock):
        url = "{}/users/info".format(settings.TSURU_HOST)
        httpretty.register_uri(
            httpretty.GET, url, status=200,
            body='{"Permissions": [{"Name":"healing.read"}, {"Name": "", "ContextType": "global"}]}'
        )
        response_mock = mock.Mock(status_code=200)
        response_mock.json.return_value = {"token": "xpto"}

        post_mock.return_value = response_mock

        request = RequestFactory().get('/', {"code": "somecode"})
        request.META['HTTP_HOST'] = 'localhost:3333'
        request.session = {"next_url": "/apps"}

        response = Callback.as_view()(request)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, "/apps")

        self.assertEqual(request.session["tsuru_token"], "type xpto")
        self.assertDictEqual(request.session["permissions"], {"healing": True, "admin": True})

        expected_url = 'http://localhost:8080/auth/login'
        expected_data = {
            "redirectUrl": "http://localhost:3333/auth/callback/",
            "code": "somecode"
        }

        post_mock.assert_called_with(expected_url, data=expected_data)