How to use request method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

wsgi_request_info_test.py

Source: wsgi_request_info_test.py Github

copy
1#!/usr/bin/env python
2#
3# Copyright 2007 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17"""Tests for google.apphosting.tools.devappserver2.wsgi_request_info."""
18
19
20import re
21import unittest
22import wsgiref.util
23
24from google.appengine.tools.devappserver2 import wsgi_request_info
25
26
27class TestWSGIRequestInfo(unittest.TestCase):
28  """Tests for WSGIRequestInfo."""
29
30  def setUp(self):
31    self.dispatcher = object()
32    self.request_info = wsgi_request_info.WSGIRequestInfo(self.dispatcher)
33
34  def _assert_request_id(self, request_id):
35    self.assertTrue(re.match('[a-zA-Z]{10}$', request_id),
36                    'invalid request id: %r' % request_id)
37
38  def _create_environ(self, scheme, host, path='', query=''):
39    environ = {'wsgi.url_scheme': scheme,
40               'HTTP_HOST': host,
41               'PATH_INFO': path,
42               'QUERY_STRING': query}
43    wsgiref.util.setup_testing_defaults(environ)
44    return environ
45
46  def _create_module_configuration(self, module_name, version_id):
47    class ModuleConfiguration(object):
48      pass
49
50    config = ModuleConfiguration()
51    config.major_version = version_id
52    config.module_name = module_name
53    return config
54
55  def test_get_request_url(self):
56    with self.request_info.request(
57        self._create_environ('https', 'machine:8080',
58                             '/foo', 'bar=baz'),
59        self._create_module_configuration('default', '1')) as request_id:
60      self._assert_request_id(request_id)
61      self.assertEqual('https://machine:8080/foo?bar=baz',
62                       self.request_info.get_request_url(request_id))
63
64  def test_get_request_environ(self):
65    environ = object()
66    with self.request_info.request(
67        environ,
68        self._create_module_configuration('default', '1')) as request_id:
69      self._assert_request_id(request_id)
70      self.assertIs(environ, self.request_info.get_request_environ(request_id))
71
72  def test_get_dispatcher(self):
73    with self.request_info.request(
74        self._create_environ('https', 'machine:8080',
75                             '/foo', 'bar=baz'),
76        self._create_module_configuration('default', '1')) as request_id:
77      self._assert_request_id(request_id)
78      self.assertEqual(self.dispatcher,
79                       self.request_info.get_dispatcher())
80
81  def test_get_module(self):
82    with self.request_info.request(
83        self._create_environ('https', 'machine:8080',
84                             '/foo', 'bar=baz'),
85        self._create_module_configuration('default', '1')) as request_id:
86      self._assert_request_id(request_id)
87      self.assertEqual('default', self.request_info.get_module(request_id))
88
89  def test_get_version(self):
90    with self.request_info.request(
91        self._create_environ('https', 'machine:8080',
92                             '/foo', 'bar=baz'),
93        self._create_module_configuration('default', '1')) as request_id:
94      self._assert_request_id(request_id)
95      self.assertEqual('1', self.request_info.get_version(request_id))
96
97  def test_get_instance_unset(self):
98    with self.request_info.request(
99        self._create_environ('https', 'machine:8080',
100                             '/foo', 'bar=baz'),
101        self._create_module_configuration('default', '1')) as request_id:
102      self._assert_request_id(request_id)
103      self.assertIsNone(self.request_info.get_instance(request_id))
104
105  def test_get_instance(self):
106    with self.request_info.request(
107        self._create_environ('https', 'machine:8080',
108                             '/foo', 'bar=baz'),
109        self._create_module_configuration('default', '1')) as request_id:
110      instance = object()
111      self.request_info.set_request_instance(request_id, instance)
112      self._assert_request_id(request_id)
113      self.assertEqual(instance, self.request_info.get_instance(request_id))
114
115  def test_concurrent_requests(self):
116    request_id1 = self.request_info.start_request(
117        self._create_environ('http', 'machine:8081'),
118        self._create_module_configuration('default', '1'))
119    request_id2 = self.request_info.start_request(
120        self._create_environ('http', 'machine:8082'),
121        self._create_module_configuration('default', '2'))
122    request_id3 = self.request_info.start_request(
123        self._create_environ('http', 'machine:8083'),
124        self._create_module_configuration('other', '1'))
125
126    self._assert_request_id(request_id1)
127    self._assert_request_id(request_id2)
128    self._assert_request_id(request_id3)
129    self.assertTrue(request_id1 != request_id2 != request_id3)
130
131    self.assertEqual('http://machine:8081/',
132                     self.request_info.get_request_url(request_id1))
133    self.assertEqual(self.dispatcher,
134                     self.request_info.get_dispatcher())
135    self.assertEqual('default', self.request_info.get_module(request_id1))
136    self.assertEqual('1', self.request_info.get_version(request_id1))
137    self.assertEqual('http://machine:8082/',
138                     self.request_info.get_request_url(request_id2))
139    self.assertEqual(self.dispatcher,
140                     self.request_info.get_dispatcher())
141    self.assertEqual('default', self.request_info.get_module(request_id2))
142    self.assertEqual('2', self.request_info.get_version(request_id2))
143    self.request_info.end_request(request_id1)
144    self.request_info.end_request(request_id2)
145    self.assertEqual('http://machine:8083/',
146                     self.request_info.get_request_url(request_id3))
147    self.assertEqual(self.dispatcher,
148                     self.request_info.get_dispatcher())
149    self.assertEqual('other', self.request_info.get_module(request_id3))
150    self.assertEqual('1', self.request_info.get_version(request_id3))
151
152if __name__ == '__main__':
153  unittest.main()
154
Full Screen

student.py

Source: student.py Github

copy
1from django.shortcuts import render, HttpResponse, redirect
2from .models import Account, Admission, Student
3from django.db import IntegrityError
4from .decorator import allowed_users
5from django.contrib.auth.decorators import login_required
6import datetime
7import secrets, random
8import string
9import datetime
10
11year_s = datetime.datetime.today().year
12YEARS = list(range(year_s, year_s - 6, -1))
13
14
15def gen():
16    N = 7
17    res = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(N))
18    res = 'PCMT' + str(datetime.datetime.today().year) + res
19    return res
20
21
22@login_required(login_url='college:login')
23def studentsRegistration(request):
24    if request.POST:
25        # try:
26        if request.POST.get('email'):
27            try:
28                enrollment_no = gen()
29                add_user = Account()
30                add_user.email = request.POST.get('email')
31                request.session['student_email'] = request.POST.get('email')
32                print(request.session['student_email'])
33                add_user.enrollment_no = enrollment_no
34
35                add_user.set_password(enrollment_no)
36                add_user.is_student = True
37                add_user.is_approved = True
38                add_user.save()
39                print('hello')
40                user = Student()
41                user.semester = request.POST.get('semester')
42                user.year = str(datetime.datetime.today().year)
43                user.student_data = add_user
44                user.enrollment_no = enrollment_no
45                user.email = request.POST.get('email')
46                user.contact_no = request.POST.get('contact_no')
47
48                user.first_name = request.POST.get('first_name')
49                user.last_name = request.POST.get('last_name')
50                user.dob = request.POST.get('dob')
51                user.gender = request.POST.get('gender')
52
53                user.address = request.POST.get('address')
54                user.city = request.POST.get('city')
55                user.state = request.POST.get('state')
56                user.country = request.POST.get('country')
57
58                user.fathers_name = request.POST.get('fathers_name')
59                user.mothers_name = request.POST.get('mothers_name')
60                user.blood_group = request.POST.get('blood_group')
61                user.mothers_tongue = request.POST.get('mothers_tongue')
62
63                user.fathers_contact_no = request.POST.get('fathers_contact_no')
64                user.guardian_name = request.POST.get('guardian_name')
65                user.guardian_contact_no = request.POST.get('guardian_contact_no')
66                user.relation_with_guardian = request.POST.get('relation_with_guardian')
67
68                user.nationality = request.POST.get('nationality')
69                user.cast = request.POST.get('cast')
70                user.religion = request.POST.get('religion')
71                user.physically_challenge = request.POST.get('physically_challenge')
72
73                user.department = request.POST.get('department')
74                user.aadhar_card_no = request.POST.get('aadhar_card_no')
75                user.save()
76
77                user.physically_certificate = request.FILES.get('physically_certificate')
78                user.cast_certificate = request.FILES.get('cast_certificate')
79                user.photo = request.FILES.get('photo')
80                user.aadhar_card = request.FILES.get('aadhar_card')
81
82                user.saveQrCode(enrollment_no=enrollment_no)
83                user.save()
84                msg = "Saved successfully"
85                color = 'success'
86                return render(request, 'registration.html', {'msg': msg, 'color': color})
87            except:
88                if Student.objects.filter(email=request.session['student_email']).count():
89                    msg = "Fill Entrance Examination field"
90                    color = 'danger'
91                    print('hello', Student.objects.filter(email=request.session['student_email']).count)
92                    return render(request, 'registration.html', {'msg': msg, 'color': color})
93                else:
94                    msg = "Try fill all the filed"
95                    color = 'danger'
96                    return render(request, 'registration.html', {'msg': msg, 'color': color})
97        elif request.POST.get('admission_cat'):
98            try:
99                user = Student.objects.get(email=request.session['student_email'])
100                user.admission_cat = request.POST.get('admission_cat')
101                user.conducted_by = request.POST.get('conducted_by')
102                user.rank = request.POST.get('rank')
103                user.roll_no = request.POST.get('roll_no')
104
105                user.allotment = request.POST.get('allotment')
106                user.admit_card = request.FILES.get('admit_card')
107                user.rank_card = request.FILES.get('rank_card')
108                user.roll_no = request.POST.get('roll_no')
109                user.save()
110                msg = "Saved successfully And Fill Education information 10th"
111                color = 'success'
112                return render(request, 'registration.html', {'msg': msg, 'color': color})
113            except:
114                msg = "Entrance examination fill all field"
115                color = 'danger'
116                return render(request, 'registration.html', {'msg': msg, 'color': color})
117        elif request.POST.get('school_name_10'):
118            try:
119                user = Student.objects.get(email=request.session['student_email'])
120                user.school_name_10 = request.POST.get('school_name_10')
121                user.board_10 = request.POST.get('board_10')
122                user.medium_10 = request.POST.get('medium_10')
123
124                user.address10 = request.POST.get('address10')
125                user.city10 = request.POST.get('city10')
126                user.state10 = request.POST.get('state10')
127                user.country10 = request.POST.get('country10')
128                user.passing_year_10 = request.POST.get('passing_year_10')
129
130                user.sub1 = request.POST.get('sub1')
131                user.sub2 = request.POST.get('sub2')
132                user.sub3 = request.POST.get('sub3')
133                user.sub4 = request.POST.get('sub4')
134                user.sub5 = request.POST.get('sub5')
135                user.aggregate10 = request.POST.get('aggregate10')
136
137                user.mark10 = request.FILES.get('mark10')
138                user.admit10 = request.FILES.get('admit10')
139                user.certificate10 = request.FILES.get('certificate10')
140                user.save()
141                msg = "Saved successfully And Fill 12th or Diploma form"
142                color = 'success'
143                return render(request, 'new_enrollment.html', {'msg': msg, 'color': color})
144            except:
145                msg = "Fill Education information 10th all field correctly"
146                color = 'danger'
147                return render(request, 'registration.html', {'msg': msg, 'color': color})
148        elif request.POST.get('diploma_or_12') == '12th':
149            try:
150                user = Student.objects.get(email=request.session['student_email'])
151                user.school_name_12 = request.POST.get('school_name_12')
152                user.board_12 = request.POST.get('board_12')
153                user.medium_12 = request.POST.get('medium_12')
154
155                user.address12 = request.POST.get('address12')
156                user.city12 = request.POST.get('city12')
157                user.state12 = request.POST.get('state12')
158                user.country12 = request.POST.get('country12')
159                user.passing_year_12 = request.POST.get('passing_year_12')
160
161                user.english = request.POST.get('english')
162                user.chemistry = request.POST.get('chemistry')
163                user.physics = request.POST.get('physics')
164                user.math = request.POST.get('math')
165                user.optional = request.POST.get('optional')
166                user.aggregate12 = request.POST.get('aggregate12')
167
168                user.mark12 = request.FILES.get('mark12')
169                user.admit12 = request.FILES.get('admit12')
170                user.certificate12 = request.FILES.get('certificate12')
171                user.save()
172                msg = "Saved successfully And Fill others form"
173                color = 'success'
174                return render(request, 'registration.html', {'msg': msg, 'color': color})
175            except:
176                msg = "Fill Education 12th or Diploma"
177                color = 'danger'
178                return render(request, 'registration.html', {'msg': msg, 'color': color})
179        elif request.POST.get('diploma_or_12') == 'diploma':
180            try:
181                user = Student.objects.get(email=request.session['student_email'])
182                user.school_name_diploma = request.POST.get('school_name_diploma')
183                user.board_diploma = request.POST.get('board_diploma')
184                user.medium_diploma = request.POST.get('medium_diploma')
185
186                user.addressDiploma = request.POST.get('addressDiploma')
187                user.cityDiploma = request.POST.get('cityDiploma')
188                user.stateDiploma = request.POST.get('stateDiploma')
189                user.countryDiploma = request.POST.get('countryDiploma')
190                user.passing_year_Diploma = request.POST.get('passing_year_Diploma')
191
192                user.marksDiploma = request.POST.get('marksDiploma')
193                user.aggregateDiploma = request.POST.get('aggregateDiploma')
194                user.division = request.POST.get('division')
195                user.markDiploma = request.FILES.get('markDiploma')
196                user.certificateDiploma = request.FILES.get('certificateDiploma')
197                user.save()
198                msg = "Saved successfully And Fill others form"
199                color = 'success'
200                return render(request, 'registration.html', {'msg': msg, 'color': color})
201            except:
202                msg = "Fill Education 12th or Diploma"
203                color = 'danger'
204                return render(request, 'registration.html', {'msg': msg, 'color': color})
205        elif request.POST.get('loan'):
206            try:
207                user = Student.objects.get(email=request.session['student_email'])
208                user.loan = request.POST.get('loan')
209                user.gap = request.POST.get('gap')
210                user.reason = request.POST.get('reason')
211                user.hostel = request.POST.get('hostel')
212                user.save()
213                msg = "Saved successfully"
214                color = 'success'
215                return render(request, 'registration.html', {'msg': msg, 'color': color})
216            except:
217                msg = "Try fill all fields"
218                color = 'danger'
219                return render(request, 'registration.html', {'msg': msg, 'color': color})
220
221    return render(request, 'registration.html', )
222
223
224@login_required(login_url='college:login')
225def student_data_view(request):
226    if request.POST and not request.user.is_student:
227        if request.POST.get('university_roll') and not request.user.is_student:
228            university_roll = request.POST.get('university_roll')
229            User = Student.objects.get(university_roll=university_roll)
230            return render(request, "student_data_view.html", context={'user': User, 'YEARS': YEARS})
231        else:
232            year = request.POST.get('go_year')
233            semester = request.POST.get('go_semester')
234            User = Student.objects.filter(semester=semester, year=year)
235            return render(request, "student_data_view.html", context={'user': User, 'YEARS': YEARS})
236    elif request.user.is_HOD:
237        user = {}
238        return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})
239    elif request.user.is_admin:
240        user = {}
241        return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})
242    elif request.user.is_student:
243        user = Student.objects.filter(email=request.session['email'])
244        return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})
245
246    elif request.user.is_BOC:
247        # user = Student.objects.filter(is_student=True, year=request.user.year, semester=request.user.semester)
248        user = {}
249        return render(request, "student_data_view.html", context={'user': user, 'YEARS': YEARS})
250    return render(request, "student_data_view.html", context={'YEARS': YEARS})
251
Full Screen

product_request_item_views.py

Source: product_request_item_views.py Github

copy
1from django.contrib import messages
2from django.http import HttpResponse, HttpResponseForbidden, HttpResponseNotFound
3from django.shortcuts import redirect
4from django.shortcuts import render
5from django.urls import reverse
6from django.views.decorators.csrf import csrf_exempt
7
8from app import settings
9from app.models import Operators, Product_Requests, Product_Request_Items, Products
10from app.utils import Utils
11from backend.forms.product_request_item_forms import ProductRequestItemCreateForm, ProductRequestItemUpdateForm
12
13
14# noinspection PyUnusedLocal, PyShadowingBuiltins
15def create(request, id):
16    template_url = 'product-request-items/create.html'
17    operator = Operators.login_required(request)
18    if operator is None:
19        Operators.set_redirect_field_name(request, request.path)
20        return redirect(reverse("operators_signin"))
21    else:
22        auth_permissions = Operators.get_auth_permissions(operator)
23        if settings.ACCESS_PERMISSION_ORDER_CREATE in auth_permissions.values():
24            try:
25                product_request = Product_Requests.objects.get(product_request_id=id)
26                if request.method == 'POST':
27
28                    form = ProductRequestItemCreateForm(request.POST)
29                    # noinspection PyArgumentList
30                    if form.is_valid():
31                        model = Product_Request_Items()
32                        model.product_requests_product_request_id = product_request.product_request_id
33                        model.products_product_id = form.cleaned_data['products_product_id']
34
35                        product = Products.objects.get(product_id=model.products_product_id)
36
37                        model.product_request_item_product_type = product.product_type
38                        model.product_request_item_product_code = product.product_code
39                        model.product_request_item_product_tag = product.product_tag
40                        model.product_request_item_product_category = product.product_category
41                        model.product_request_item_product_title = product.product_title
42                        model.product_request_item_product_sub_title = product.product_sub_title
43                        model.product_request_item_product_quantity_initial = 0
44                        model.product_request_item_product_quantity_ordered = form.cleaned_data[
45                            'product_request_item_product_quantity_ordered']
46                        model.product_request_item_product_quantity_balance = 0
47                        model.product_request_item_product_quantity_unit = product.product_quantity_unit
48
49                        model.product_request_item_created_at = Utils.get_current_datetime_utc()
50                        model.product_request_item_created_id = operator.operator_id
51                        model.product_request_item_created_by = operator.operator_name
52                        model.product_request_item_created_department = operator.operator_department
53                        model.product_request_item_created_role = operator.operator_role
54
55                        model.product_request_item_updated_at = Utils.get_current_datetime_utc()
56                        model.product_request_item_updated_id = operator.operator_id
57                        model.product_request_item_updated_by = operator.operator_name
58                        model.product_request_item_updated_department = operator.operator_department
59                        model.product_request_item_updated_role = operator.operator_role
60
61                        model.product_request_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
62                        model.product_request_item_received_id = ''
63                        model.product_request_item_received_by = ''
64                        model.product_request_item_received_department = ''
65                        model.product_request_item_received_role = ''
66
67                        model.product_request_item_status = Product_Requests.STATUS_PENDING
68                        # noinspection PyCallByClass,PyTypeChecker
69                        model.save('Created')
70
71                        Product_Requests.update_grand_total(request, product_request, operator)
72
73                        messages.success(request, 'Item added successfully.')
74                        return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))
75                    else:
76                        error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])
77                        messages.error(request, '' + error_string)
78                        return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))
79
80                else:
81                    form = ProductRequestItemCreateForm(
82                        initial={
83                            'product_request_id': product_request.product_request_code,
84                            'products_product_id': '',
85                            'product_request_item_product_quantity_ordered': 0,
86                        })
87
88                return render(
89                    request, template_url,
90                    {
91                        'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
92                        'title': Product_Request_Items.TITLE,
93                        'name': Product_Request_Items.NAME,
94                        'operator': operator,
95                        'auth_permissions': auth_permissions,
96                        'form': form,
97                    }
98                )
99            except(TypeError, ValueError, OverflowError,
100                   Product_Requests.DoesNotExist, Product_Request_Items.DoesNotExist):
101                return HttpResponseNotFound('Not Found', content_type='text/plain')
102        else:
103            return HttpResponseForbidden('Forbidden', content_type='text/plain')
104
105
106# noinspection PyUnusedLocal, PyShadowingBuiltins
107def update(request, pk):
108    template_url = 'product-request-items/update.html'
109    operator = Operators.login_required(request)
110    if operator is None:
111        Operators.set_redirect_field_name(request, request.path)
112        return redirect(reverse("operators_signin"))
113    else:
114        auth_permissions = Operators.get_auth_permissions(operator)
115        if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
116            try:
117                model = Product_Request_Items.objects.get(product_request_item_id=pk)
118                product_request = Product_Requests.objects.get(
119                    product_request_id=model.product_requests_product_request_id)
120                if request.method == 'POST':
121
122                    form = ProductRequestItemUpdateForm(request.POST)
123
124                    # noinspection PyArgumentList
125                    if form.is_valid():
126                        model.products_product_id = form.cleaned_data['products_product_id']
127
128                        product = Products.objects.get(product_id=model.products_product_id)
129
130                        model.product_request_item_product_type = product.product_type
131                        model.product_request_item_product_code = product.product_code
132                        model.product_request_item_product_tag = product.product_tag
133                        model.product_request_item_product_category = product.product_category
134                        model.product_request_item_product_title = product.product_title
135                        model.product_request_item_product_sub_title = product.product_sub_title
136                        model.product_request_item_product_quantity_initial = 0
137                        model.product_request_item_product_quantity_ordered = form.cleaned_data[
138                            'product_request_item_product_quantity_ordered']
139                        model.product_request_item_product_quantity_balance = 0
140                        model.product_request_item_product_quantity_unit = product.product_quantity_unit
141
142                        model.product_request_item_updated_at = Utils.get_current_datetime_utc()
143                        model.product_request_item_updated_id = operator.operator_id
144                        model.product_request_item_updated_by = operator.operator_name
145                        model.product_request_item_updated_department = operator.operator_department
146                        model.product_request_item_updated_role = operator.operator_role
147                        model.save()
148
149                        Product_Requests.update_grand_total(request, product_request, operator)
150
151                        messages.success(request, 'Item updated successfully.')
152                        return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))
153                    else:
154                        error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])
155                        messages.error(request, '' + error_string)
156                        return redirect(reverse("product_requests_view", args=[product_request.product_request_id]))
157                else:
158                    form = ProductRequestItemUpdateForm(
159                        initial={
160                            'product_request_id': product_request.product_request_code,
161                            'products_product_id': model.products_product_id,
162                            'product_request_item_product_quantity_ordered': model.product_request_item_product_quantity_ordered,
163                        }
164                    )
165
166                return render(
167                    request, template_url,
168                    {
169                        'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
170                        'title': Product_Request_Items.TITLE,
171                        'name': Product_Request_Items.NAME,
172                        'operator': operator,
173                        'auth_permissions': auth_permissions,
174                        'form': form,
175                        'model': model,
176                    }
177                )
178            except(
179                    TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist,
180                    Product_Request_Items.DoesNotExist):
181                return HttpResponseNotFound('Not Found', content_type='text/plain')
182        else:
183            return HttpResponseForbidden('Forbidden', content_type='text/plain')
184
185
186@csrf_exempt
187# noinspection PyUnusedLocal
188def select_single(request):
189    if request.is_ajax():
190        operator = Operators.login_required(request)
191        if operator is None:
192            # Operators.set_redirect_field_name(request, request.path)
193            # return redirect(reverse("operators_signin"))
194            return HttpResponse('signin', content_type='text/plain')
195        else:
196            auth_permissions = Operators.get_auth_permissions(operator)
197            action = request.POST['action']
198            id = request.POST['id']
199            if action != '' and id is not None:
200                if action == 'delete':
201                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
202                        try:
203                            model = Product_Request_Items.objects.get(product_request_item_id=id)
204                            product_request = Product_Requests.objects.get(
205                                product_request_id=model.product_requests_product_request_id)
206
207                            Product_Request_Items.delete_product_request_item(request, model, operator)
208
209                            Product_Requests.update_grand_total(request, product_request, operator)
210
211                            messages.success(request, 'Item removed successfully.')
212                        except(TypeError, ValueError, OverflowError, Product_Request_Items.DoesNotExist):
213                            return HttpResponseBadRequest('Bad Request', content_type='text/plain')
214                    else:
215                        return HttpResponseForbidden('Forbidden', content_type='text/plain')
216                return HttpResponse('success', content_type='text/plain')
217            else:
218                return HttpResponseBadRequest('Bad Request', content_type='text/plain')
219    else:
220        return HttpResponseForbidden('Forbidden', content_type='text/plain')
221
222
223@csrf_exempt
224# noinspection PyUnusedLocal
225def select_multiple(request):
226    if request.is_ajax():
227        operator = Operators.login_required(request)
228        if operator is None:
229            # Operators.set_redirect_field_name(request, request.path)
230            # return redirect(reverse("operators_signin"))
231            return HttpResponse('signin', content_type='text/plain')
232        else:
233            auth_permissions = Operators.get_auth_permissions(operator)
234            action = request.POST['action']
235            ids = request.POST['ids']
236            try:
237                ids = ids.split(",")
238            except(TypeError, ValueError, OverflowError):
239                ids = None
240            if action != '' and ids is not None:
241                if action == 'order-item-received':
242                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
243                        for id in ids:
244                            try:
245                                model = Product_Request_Items.objects.get(product_request_item_id=id)
246                                if model.product_request_item_status == Product_Request_Items.STATUS_PENDING:
247                                    try:
248                                        product = Products.objects.get(product_id=model.products_product_id)
249
250                                        model.product_request_item_product_quantity_initial = product.product_quantity_available
251
252                                        product.product_quantity_available = product.product_quantity_available - model.product_request_item_product_quantity_ordered
253
254                                        model.product_request_item_product_quantity_balance = product.product_quantity_available
255
256                                        product.product_updated_at = Utils.get_current_datetime_utc()
257                                        product.product_updated_id = operator.operator_id
258                                        product.product_updated_by = operator.operator_name
259                                        product.product_updated_department = operator.operator_department
260                                        product.product_updated_role = operator.operator_role
261                                        product.save()
262                                    except (Product_Requests.DoesNotExist, Products.DoesNotExist):
263                                        print('Product Request does not exist.')
264
265                                    model.product_request_item_received_at = Utils.get_current_datetime_utc()
266                                    model.product_request_item_received_id = operator.operator_id
267                                    model.product_request_item_received_by = operator.operator_name
268                                    model.product_request_item_received_department = operator.operator_department
269                                    model.product_request_item_received_role = operator.operator_role
270                                    model.product_request_item_status = Product_Request_Items.STATUS_RECEIVED
271                                    model.save()
272
273                            except(TypeError, ValueError, OverflowError, Product_Request_Items.DoesNotExist):
274                                continue
275                        messages.success(request, 'Updated successfully.')
276                    else:
277                        return HttpResponseForbidden('Forbidden', content_type='text/plain')
278                if action == 'order-item-pending':
279                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
280                        for id in ids:
281                            try:
282                                model = Product_Request_Items.objects.get(product_request_item_id=id)
283                                if model.product_request_item_status == Product_Request_Items.STATUS_RECEIVED:
284                                    try:
285                                        product = Products.objects.get(product_id=model.products_product_id)
286
287                                        model.product_request_item_product_quantity_initial = 0
288
289                                        product.product_quantity_available = product.product_quantity_available + model.product_request_item_product_quantity_ordered
290
291                                        model.product_request_item_product_quantity_balance = 0
292
293                                        product.product_updated_at = Utils.get_current_datetime_utc()
294                                        product.product_updated_id = operator.operator_id
295                                        product.product_updated_by = operator.operator_name
296                                        product.product_updated_department = operator.operator_department
297                                        product.product_updated_role = operator.operator_role
298                                        product.save()
299                                    except (Product_Requests.DoesNotExist, Products.DoesNotExist):
300                                        print('Product Request not exist.')
301
302                                    model.product_request_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
303                                    model.product_request_item_received_id = ''
304                                    model.product_request_item_received_by = ''
305                                    model.product_request_item_received_department = ''
306                                    model.product_request_item_received_role = ''
307                                    model.product_request_item_status = Product_Request_Items.STATUS_PENDING
308                                    model.save()
309
310                            except(TypeError, ValueError, OverflowError, Product_Request_Items.DoesNotExist):
311                                continue
312                        messages.success(request, 'Updated successfully.')
313                    else:
314                        return HttpResponseForbidden('Forbidden', content_type='text/plain')
315
316                return HttpResponse('success', content_type='text/plain')
317            else:
318                return HttpResponseBadRequest('Bad Request', content_type='text/plain')
319    else:
320        return HttpResponseForbidden('Forbidden', content_type='text/plain')
321
Full Screen

fakeRequestSpec.js

Source: fakeRequestSpec.js Github

copy
1describe('FakeRequest', function() {
2  beforeEach(function() {
3    this.requestTracker = { track: jasmine.createSpy('trackRequest') };
4    this.stubTracker = { findStub: function() {} };
5    var parserInstance = this.parserInstance = jasmine.createSpy('parse');
6    this.paramParser = { findParser: function() { return { parse: parserInstance }; } };
7    this.fakeGlobal = {
8      XMLHttpRequest: function() {
9        this.extraAttribute = 'my cool attribute';
10      },
11      DOMParser: window.DOMParser,
12      ActiveXObject: window.ActiveXObject
13    };
14    this.FakeRequest = getJasmineRequireObj().AjaxFakeRequest()(this.fakeGlobal, this.requestTracker, this.stubTracker, this.paramParser);
15  });
16
17  it('extends from the global XMLHttpRequest', function() {
18    var request = new this.FakeRequest();
19
20    expect(request.extraAttribute).toEqual('my cool attribute');
21  });
22
23  it('skips XMLHttpRequest attributes that IE does not want copied', function() {
24    // use real window here so it will correctly go red on IE if it breaks
25    var FakeRequest = getJasmineRequireObj().AjaxFakeRequest()(window, this.requestTracker, this.stubTracker, this.paramParser);
26    var request = new FakeRequest();
27
28    expect(request.responseBody).toBeUndefined();
29    expect(request.responseXML).toBeUndefined();
30    expect(request.statusText).toBeUndefined();
31  });
32
33  it('tracks the request', function() {
34    var request = new this.FakeRequest();
35
36    expect(this.requestTracker.track).toHaveBeenCalledWith(request);
37  });
38
39  it('has default request headers and override mime type', function() {
40    var request = new this.FakeRequest();
41
42    expect(request.requestHeaders).toEqual({});
43    expect(request.overriddenMimeType).toBeNull();
44  });
45
46  it('saves request information when opened', function() {
47    var request = new this.FakeRequest();
48    request.open('METHOD', 'URL', 'ignore_async', 'USERNAME', 'PASSWORD');
49
50    expect(request.method).toEqual('METHOD');
51    expect(request.url).toEqual('URL');
52    expect(request.username).toEqual('USERNAME');
53    expect(request.password).toEqual('PASSWORD');
54  });
55
56  it('saves an override mime type', function() {
57    var request = new this.FakeRequest();
58
59    request.overrideMimeType('application/text; charset: utf-8');
60
61    expect(request.overriddenMimeType).toBe('application/text; charset: utf-8');
62  });
63
64  it('saves request headers', function() {
65    var request = new this.FakeRequest();
66
67    request.setRequestHeader('X-Header-1', 'value1');
68    request.setRequestHeader('X-Header-2', 'value2');
69
70    expect(request.requestHeaders).toEqual({
71      'X-Header-1': 'value1',
72      'X-Header-2': 'value2'
73    });
74  });
75
76  it('combines request headers with the same header name', function() {
77    var request = new this.FakeRequest();
78
79    request.setRequestHeader('X-Header', 'value1');
80    request.setRequestHeader('X-Header', 'value2');
81
82    expect(request.requestHeaders['X-Header']).toEqual('value1, value2');
83  });
84
85  it('finds the content-type request header', function() {
86    var request = new this.FakeRequest();
87
88    request.setRequestHeader('ContEnt-tYPe', 'application/text+xml');
89
90    expect(request.contentType()).toEqual('application/text+xml');
91  });
92
93  describe('managing readyState', function() {
94    beforeEach(function() {
95      this.request = new this.FakeRequest();
96      this.request.onreadystatechange = jasmine.createSpy('onreadystatechange');
97    });
98
99    it('has an initial ready state of 0 (uninitialized)', function() {
100      expect(this.request.readyState).toBe(0);
101      expect(this.request.onreadystatechange).not.toHaveBeenCalled();
102    });
103
104    it('has a ready state of 1 (open) when opened', function() {
105      this.request.open();
106
107      expect(this.request.readyState).toBe(1);
108      expect(this.request.onreadystatechange).toHaveBeenCalled();
109    });
110
111    it('has a ready state of 0 (uninitialized) when aborted', function() {
112      this.request.open();
113      this.request.onreadystatechange.calls.reset();
114
115      this.request.abort();
116
117      expect(this.request.readyState).toBe(0);
118      expect(this.request.onreadystatechange).toHaveBeenCalled();
119    });
120
121    it('has a ready state of 2 (sent) when sent', function() {
122      this.request.open();
123      this.request.onreadystatechange.calls.reset();
124
125      this.request.send();
126
127      expect(this.request.readyState).toBe(2);
128      expect(this.request.onreadystatechange).toHaveBeenCalled();
129    });
130
131    it('has a ready state of 4 (loaded) when timed out', function() {
132      this.request.open();
133      this.request.send();
134      this.request.onreadystatechange.calls.reset();
135
136      jasmine.clock().install();
137      this.request.responseTimeout();
138      jasmine.clock().uninstall();
139
140      expect(this.request.readyState).toBe(4);
141      expect(this.request.onreadystatechange).toHaveBeenCalledWith('timeout');
142    });
143
144    it('has a ready state of 4 (loaded) when network erroring', function() {
145      this.request.open();
146      this.request.send();
147      this.request.onreadystatechange.calls.reset();
148
149      this.request.responseError();
150
151      expect(this.request.readyState).toBe(4);
152      expect(this.request.onreadystatechange).toHaveBeenCalled();
153    });
154
155    it('has a ready state of 4 (loaded) when responding', function() {
156      this.request.open();
157      this.request.send();
158      this.request.onreadystatechange.calls.reset();
159
160      this.request.response({});
161
162      expect(this.request.readyState).toBe(4);
163      expect(this.request.onreadystatechange).toHaveBeenCalled();
164    });
165
166    it('throws an error when timing out a request that has completed', function() {
167      this.request.open();
168      this.request.send();
169      this.request.response({});
170      var request = this.request;
171
172      expect(function() {
173        request.responseTimeout();
174      }).toThrowError('FakeXMLHttpRequest already completed');
175    });
176
177    it('throws an error when responding to a request that has completed', function() {
178      this.request.open();
179      this.request.send();
180      this.request.response({});
181      var request = this.request;
182
183      expect(function() {
184        request.response({});
185      }).toThrowError('FakeXMLHttpRequest already completed');
186    });
187
188    it('throws an error when erroring a request that has completed', function() {
189      this.request.open();
190      this.request.send();
191      this.request.response({});
192      var request = this.request;
193
194      expect(function() {
195        request.responseError({});
196      }).toThrowError('FakeXMLHttpRequest already completed');
197    });
198  });
199
200  describe('triggering progress events', function() {
201    beforeEach(function() {
202      this.request = new this.FakeRequest();
203
204      spyOn(this.request, 'onloadstart');
205      spyOn(this.request, 'onprogress');
206      spyOn(this.request, 'onabort');
207      spyOn(this.request, 'onerror');
208      spyOn(this.request, 'onload');
209      spyOn(this.request, 'ontimeout');
210      spyOn(this.request, 'onloadend');
211
212      var spies = {};
213
214      spies.loadstart1 = jasmine.createSpy('loadstart1');
215      spies.loadstart2 = jasmine.createSpy('loadstart2');
216      this.request.addEventListener('loadstart', spies.loadstart1);
217      this.request.addEventListener('loadstart', spies.loadstart2);
218
219      spies.progress1 = jasmine.createSpy('progress1');
220      spies.progress2 = jasmine.createSpy('progress2');
221      this.request.addEventListener('progress', spies.progress1);
222      this.request.addEventListener('progress', spies.progress2);
223
224      spies.abort1 = jasmine.createSpy('abort1');
225      spies.abort2 = jasmine.createSpy('abort2');
226      this.request.addEventListener('abort', spies.abort1);
227      this.request.addEventListener('abort', spies.abort2);
228
229      spies.error1 = jasmine.createSpy('error1');
230      spies.error2 = jasmine.createSpy('error2');
231      this.request.addEventListener('error', spies.error1);
232      this.request.addEventListener('error', spies.error2);
233
234      spies.load1 = jasmine.createSpy('load1');
235      spies.load2 = jasmine.createSpy('load2');
236      this.request.addEventListener('load', spies.load1);
237      this.request.addEventListener('load', spies.load2);
238
239      spies.timeout1 = jasmine.createSpy('timeout1');
240      spies.timeout2 = jasmine.createSpy('timeout2');
241      this.request.addEventListener('timeout', spies.timeout1);
242      this.request.addEventListener('timeout', spies.timeout2);
243
244      spies.loadend1 = jasmine.createSpy('loadend1');
245      spies.loadend2 = jasmine.createSpy('loadend2');
246      this.request.addEventListener('loadend', spies.loadend1);
247      this.request.addEventListener('loadend', spies.loadend2);
248
249      this.resetEvents = function() {
250        var request = this.request;
251        var events = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend'];
252        for (var index in events) {
253          var event = events[index];
254          request['on' + event].calls.reset();
255          spies[event + '1'].calls.reset();
256          spies[event + '2'].calls.reset();
257        }
258      };
259
260      jasmine.addMatchers({
261        toHaveTriggeredEvent: function(util) {
262          return {
263            compare: function(actual, expected) {
264              var direct = actual['on' + expected].calls.any();
265              var event1 = spies[expected + '1'].calls.any();
266              var event2 = spies[expected + '2'].calls.any();
267              var pass = direct && event1 && event2;
268
269              var missed = [], triggered = [];
270
271              (direct ? triggered : missed).push('direct');
272              (event1 ? triggered : missed).push(expected + '1');
273              (event2 ? triggered : missed).push(expected + '2');
274
275              return {
276                pass: pass,
277                message: pass ?
278                  'Expected XHR not to have triggered ' + expected + ' but ' + triggered.join(', ') + ' triggered' :
279                  'Expected XHR to have triggered ' + expected + ' but ' + missed.join(', ') + " didn't trigger"
280              };
281            }
282          };
283        }
284      });
285    });
286
287    it('should not trigger any events to start', function() {
288      this.request.open();
289
290      expect(this.request).not.toHaveTriggeredEvent('loadstart');
291      expect(this.request).not.toHaveTriggeredEvent('progress');
292      expect(this.request).not.toHaveTriggeredEvent('abort');
293      expect(this.request).not.toHaveTriggeredEvent('error');
294      expect(this.request).not.toHaveTriggeredEvent('load');
295      expect(this.request).not.toHaveTriggeredEvent('timeout');
296      expect(this.request).not.toHaveTriggeredEvent('loadend');
297    });
298
299    it('should trigger loadstart when sent', function() {
300      this.request.open();
301      this.request.send();
302
303      expect(this.request).toHaveTriggeredEvent('loadstart');
304      expect(this.request).not.toHaveTriggeredEvent('progress');
305      expect(this.request).not.toHaveTriggeredEvent('abort');
306      expect(this.request).not.toHaveTriggeredEvent('error');
307      expect(this.request).not.toHaveTriggeredEvent('load');
308      expect(this.request).not.toHaveTriggeredEvent('timeout');
309      expect(this.request).not.toHaveTriggeredEvent('loadend');
310    });
311
312    it('should trigger abort, progress, loadend when aborted', function() {
313      this.request.open();
314      this.request.send();
315
316      this.resetEvents();
317
318      this.request.abort();
319
320      expect(this.request).not.toHaveTriggeredEvent('loadstart');
321      expect(this.request).toHaveTriggeredEvent('progress');
322      expect(this.request).toHaveTriggeredEvent('abort');
323      expect(this.request).not.toHaveTriggeredEvent('error');
324      expect(this.request).not.toHaveTriggeredEvent('load');
325      expect(this.request).not.toHaveTriggeredEvent('timeout');
326      expect(this.request).toHaveTriggeredEvent('loadend');
327    });
328
329    it('should trigger error, progress, loadend when network error', function() {
330      this.request.open();
331      this.request.send();
332
333      this.resetEvents();
334
335      this.request.responseError();
336
337      expect(this.request).not.toHaveTriggeredEvent('loadstart');
338      expect(this.request).toHaveTriggeredEvent('progress');
339      expect(this.request).not.toHaveTriggeredEvent('abort');
340      expect(this.request).toHaveTriggeredEvent('error');
341      expect(this.request).not.toHaveTriggeredEvent('load');
342      expect(this.request).not.toHaveTriggeredEvent('timeout');
343      expect(this.request).toHaveTriggeredEvent('loadend');
344    });
345
346    it('should trigger timeout, progress, loadend when timing out', function() {
347      this.request.open();
348      this.request.send();
349
350      this.resetEvents();
351
352      jasmine.clock().install();
353      this.request.responseTimeout();
354      jasmine.clock().uninstall();
355
356      expect(this.request).not.toHaveTriggeredEvent('loadstart');
357      expect(this.request).toHaveTriggeredEvent('progress');
358      expect(this.request).not.toHaveTriggeredEvent('abort');
359      expect(this.request).not.toHaveTriggeredEvent('error');
360      expect(this.request).not.toHaveTriggeredEvent('load');
361      expect(this.request).toHaveTriggeredEvent('timeout');
362      expect(this.request).toHaveTriggeredEvent('loadend');
363    });
364
365    it('should trigger load, progress, loadend when responding', function() {
366      this.request.open();
367      this.request.send();
368
369      this.resetEvents();
370
371      this.request.response({ status: 200 });
372
373      expect(this.request).not.toHaveTriggeredEvent('loadstart');
374      expect(this.request).toHaveTriggeredEvent('progress');
375      expect(this.request).not.toHaveTriggeredEvent('abort');
376      expect(this.request).not.toHaveTriggeredEvent('error');
377      expect(this.request).toHaveTriggeredEvent('load');
378      expect(this.request).not.toHaveTriggeredEvent('timeout');
379      expect(this.request).toHaveTriggeredEvent('loadend');
380    });
381  });
382
383  it('ticks the jasmine clock on timeout', function() {
384    var clock = { tick: jasmine.createSpy('tick') };
385    spyOn(jasmine, 'clock').and.returnValue(clock);
386
387    var request = new this.FakeRequest();
388    request.open();
389    request.send();
390
391    request.responseTimeout();
392
393    expect(clock.tick).toHaveBeenCalledWith(30000);
394  });
395
396  it('has an initial status of null', function() {
397    var request = new this.FakeRequest();
398
399    expect(request.status).toBeNull();
400  });
401
402  it('has an aborted status', function() {
403    var request = new this.FakeRequest();
404
405    request.abort();
406
407    expect(request.status).toBe(0);
408    expect(request.statusText).toBe('abort');
409  });
410
411  it('has a status from the response', function() {
412    var request = new this.FakeRequest();
413    request.open();
414    request.send();
415
416    request.response({ status: 200 });
417
418    expect(request.status).toBe(200);
419    expect(request.statusText).toBe('');
420  });
421
422  it('has a statusText from the response', function() {
423    var request = new this.FakeRequest();
424    request.open();
425    request.send();
426
427    request.response({ status: 200, statusText: 'OK' });
428
429    expect(request.status).toBe(200);
430    expect(request.statusText).toBe('OK');
431  });
432
433  it('saves off any data sent to the server', function() {
434    var request = new this.FakeRequest();
435    request.open();
436    request.send('foo=bar&baz=quux');
437
438    expect(request.params).toBe('foo=bar&baz=quux');
439  });
440
441  it('parses data sent to the server', function() {
442    var request = new this.FakeRequest();
443    request.open();
444    request.send('foo=bar&baz=quux');
445
446    this.parserInstance.and.returnValue('parsed');
447
448    expect(request.data()).toBe('parsed');
449  });
450
451  it('skips parsing if no data was sent', function() {
452    var request = new this.FakeRequest();
453    request.open();
454    request.send();
455
456    expect(request.data()).toEqual({});
457    expect(this.parserInstance).not.toHaveBeenCalled();
458  });
459
460  it('saves responseText', function() {
461    var request = new this.FakeRequest();
462    request.open();
463    request.send();
464
465    request.response({ status: 200, responseText: 'foobar' });
466
467    expect(request.responseText).toBe('foobar');
468  });
469
470  it('defaults responseText if none is given', function() {
471    var request = new this.FakeRequest();
472    request.open();
473    request.send();
474
475    request.response({ status: 200 });
476
477    expect(request.responseText).toBe('');
478  });
479
480  it('retrieves individual response headers', function() {
481    var request = new this.FakeRequest();
482    request.open();
483    request.send();
484
485    request.response({
486      status: 200,
487      responseHeaders: {
488        'X-Header': 'foo'
489      }
490    });
491
492    expect(request.getResponseHeader('X-Header')).toBe('foo');
493  });
494
495  it('retrieves individual response headers case-insensitively', function() {
496    var request = new this.FakeRequest();
497    request.open();
498    request.send();
499
500    request.response({
501      status: 200,
502      responseHeaders: {
503        'X-Header': 'foo'
504      }
505    });
506
507    expect(request.getResponseHeader('x-header')).toBe('foo');
508  });
509
510  it('retrieves a combined response header', function() {
511    var request = new this.FakeRequest();
512    request.open();
513    request.send();
514
515    request.response({
516      status: 200,
517      responseHeaders: [
518        { name: 'X-Header', value: 'foo' },
519        { name: 'X-Header', value: 'bar' }
520      ]
521    });
522
523    expect(request.getResponseHeader('x-header')).toBe('foo, bar');
524  });
525
526  it("doesn't pollute the response headers of other XHRs", function() {
527    var request1 = new this.FakeRequest();
528    request1.open();
529    request1.send();
530
531    var request2 = new this.FakeRequest();
532    request2.open();
533    request2.send();
534
535    request1.response({ status: 200, responseHeaders: { 'X-Foo': 'bar' } });
536    request2.response({ status: 200, responseHeaders: { 'X-Baz': 'quux' } });
537
538    expect(request1.getAllResponseHeaders()).toBe('X-Foo: bar');
539    expect(request2.getAllResponseHeaders()).toBe('X-Baz: quux');
540  });
541
542  it('retrieves all response headers', function() {
543    var request = new this.FakeRequest();
544    request.open();
545    request.send();
546
547    request.response({
548      status: 200,
549      responseHeaders: [
550        { name: 'X-Header-1', value: 'foo' },
551        { name: 'X-Header-2', value: 'bar' },
552        { name: 'X-Header-1', value: 'baz' }
553      ]
554    });
555
556    expect(request.getAllResponseHeaders()).toBe("X-Header-1: foo\r\nX-Header-2: bar\r\nX-Header-1: baz");
557  });
558
559  it('sets the content-type header to the specified contentType when no other headers are supplied', function() {
560    var request = new this.FakeRequest();
561    request.open();
562    request.send();
563
564    request.response({ status: 200, contentType: 'text/plain' });
565
566    expect(request.getResponseHeader('content-type')).toBe('text/plain');
567    expect(request.getAllResponseHeaders()).toBe('Content-Type: text/plain');
568  });
569
570  it('sets a default content-type header if no contentType and headers are supplied', function() {
571    var request = new this.FakeRequest();
572    request.open();
573    request.send();
574
575    request.response({ status: 200 });
576
577    expect(request.getResponseHeader('content-type')).toBe('application/json');
578    expect(request.getAllResponseHeaders()).toBe('Content-Type: application/json');
579  });
580
581  it('has no responseXML by default', function() {
582    var request = new this.FakeRequest();
583    request.open();
584    request.send();
585
586    request.response({ status: 200 });
587
588    expect(request.responseXML).toBeNull();
589  });
590
591  it('parses a text/xml document into responseXML', function() {
592    var request = new this.FakeRequest();
593    request.open();
594    request.send();
595
596    request.response({ status: 200, contentType: 'text/xml', responseText: '<dom><stuff/></dom>' });
597
598    if (typeof window.Document !== 'undefined') {
599      expect(request.responseXML instanceof window.Document).toBe(true);
600    } else {
601      // IE 8
602      expect(request.responseXML instanceof window.ActiveXObject).toBe(true);
603    }
604  });
605
606  it('parses an application/xml document into responseXML', function() {
607    var request = new this.FakeRequest();
608    request.open();
609    request.send();
610
611    request.response({ status: 200, contentType: 'application/xml', responseText: '<dom><stuff/></dom>' });
612
613    if (typeof window.Document !== 'undefined') {
614      expect(request.responseXML instanceof window.Document).toBe(true);
615    } else {
616      // IE 8
617      expect(request.responseXML instanceof window.ActiveXObject).toBe(true);
618    }
619  });
620
621  it('parses a custom blah+xml document into responseXML', function() {
622    var request = new this.FakeRequest();
623    request.open();
624    request.send();
625
626    request.response({ status: 200, contentType: 'application/text+xml', responseText: '<dom><stuff/></dom>' });
627
628    if (typeof window.Document !== 'undefined') {
629      expect(request.responseXML instanceof window.Document).toBe(true);
630    } else {
631      // IE 8
632      expect(request.responseXML instanceof window.ActiveXObject).toBe(true);
633    }
634  });
635});
636
Full Screen

NetworkManager.js

Source: NetworkManager.js Github

copy
1/*
2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 *     * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *     * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 *     * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/**
32 * @constructor
33 * @extends {WebInspector.Object}
34 */
35WebInspector.NetworkManager = function()
36{
37    WebInspector.Object.call(this);
38    this._dispatcher = new WebInspector.NetworkDispatcher(this);
39    if (WebInspector.settings.cacheDisabled.get())
40        NetworkAgent.setCacheDisabled(true);
41
42    NetworkAgent.enable();
43
44    WebInspector.settings.cacheDisabled.addChangeListener(this._cacheDisabledSettingChanged, this);
45
46    if (WebInspector.settings.userAgent.get())
47        this._userAgentSettingChanged();
48    WebInspector.settings.userAgent.addChangeListener(this._userAgentSettingChanged, this);
49}
50
51WebInspector.NetworkManager.EventTypes = {
52    ResourceTrackingEnabled: "ResourceTrackingEnabled",
53    ResourceTrackingDisabled: "ResourceTrackingDisabled",
54    RequestStarted: "RequestStarted",
55    RequestUpdated: "RequestUpdated",
56    RequestFinished: "RequestFinished",
57    RequestUpdateDropped: "RequestUpdateDropped"
58}
59
60WebInspector.NetworkManager._MIMETypes = {
61    "text/html":                   {"document": true},
62    "text/xml":                    {"document": true},
63    "text/plain":                  {"document": true},
64    "application/xhtml+xml":       {"document": true},
65    "text/css":                    {"stylesheet": true},
66    "text/xsl":                    {"stylesheet": true},
67    "image/jpeg":                  {"image": true},
68    "image/png":                   {"image": true},
69    "image/gif":                   {"image": true},
70    "image/bmp":                   {"image": true},
71    "image/svg+xml":               {"image": true},
72    "image/vnd.microsoft.icon":    {"image": true},
73    "image/webp":                  {"image": true},
74    "image/x-icon":                {"image": true},
75    "image/x-xbitmap":             {"image": true},
76    "font/ttf":                    {"font": true},
77    "font/opentype":               {"font": true},
78    "font/woff":                   {"font": true},
79    "application/x-font-type1":    {"font": true},
80    "application/x-font-ttf":      {"font": true},
81    "application/x-font-woff":     {"font": true},
82    "application/x-truetype-font": {"font": true},
83    "text/javascript":             {"script": true},
84    "text/ecmascript":             {"script": true},
85    "application/javascript":      {"script": true},
86    "application/ecmascript":      {"script": true},
87    "application/x-javascript":    {"script": true},
88    "application/json":            {"script": true},
89    "text/javascript1.1":          {"script": true},
90    "text/javascript1.2":          {"script": true},
91    "text/javascript1.3":          {"script": true},
92    "text/jscript":                {"script": true},
93    "text/livescript":             {"script": true},
94}
95
96WebInspector.NetworkManager.prototype = {
97    enableResourceTracking: function()
98    {
99        function callback(error)
100        {
101            this.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.ResourceTrackingEnabled);
102        }
103        NetworkAgent.enable(callback.bind(this));
104    },
105
106    disableResourceTracking: function()
107    {
108        function callback(error)
109        {
110            this.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.ResourceTrackingDisabled);
111        }
112        NetworkAgent.disable(callback.bind(this));
113    },
114
115    /**
116     * @param {string} url
117     * @return {WebInspector.NetworkRequest}
118     */
119    inflightRequestForURL: function(url)
120    {
121        return this._dispatcher._inflightRequestsByURL[url];
122    },
123
124    /**
125     * @param {WebInspector.Event} event
126     */
127    _cacheDisabledSettingChanged: function(event)
128    {
129        var enabled = /** @type {boolean} */ event.data;
130        NetworkAgent.setCacheDisabled(enabled);
131    },
132
133    _userAgentSettingChanged: function()
134    {
135        NetworkAgent.setUserAgentOverride(WebInspector.settings.userAgent.get());
136    }
137}
138
139WebInspector.NetworkManager.prototype.__proto__ = WebInspector.Object.prototype;
140
141/**
142 * @constructor
143 * @implements {NetworkAgent.Dispatcher}
144 */
145WebInspector.NetworkDispatcher = function(manager)
146{
147    this._manager = manager;
148    this._inflightRequestsById = {};
149    this._inflightRequestsByURL = {};
150    InspectorBackend.registerNetworkDispatcher(this);
151}
152
153WebInspector.NetworkDispatcher.prototype = {
154    /**
155     * @param {NetworkAgent.Headers} headersMap
156     * @return {Array.<Object>}
157     */
158    _headersMapToHeadersArray: function(headersMap)
159    {
160        var result = [];
161        for (var name in headersMap) {
162            var values = headersMap[name].split("\n");
163            for (var i = 0; i < values.length; ++i)
164                result.push({ name: name, value: values[i] });
165        }
166        return result;
167    },
168
169    /**
170     * @param {WebInspector.NetworkRequest} networkRequest
171     * @param {NetworkAgent.Request} request
172     */
173    _updateNetworkRequestWithRequest: function(networkRequest, request)
174    {
175        networkRequest.requestMethod = request.method;
176        networkRequest.requestHeaders = this._headersMapToHeadersArray(request.headers);
177        networkRequest.requestFormData = request.postData;
178    },
179
180    /**
181     * @param {WebInspector.NetworkRequest} networkRequest
182     * @param {NetworkAgent.Response=} response
183     */
184    _updateNetworkRequestWithResponse: function(networkRequest, response)
185    {
186        if (!response)
187            return;
188
189        if (response.url && networkRequest.url !== response.url)
190            networkRequest.url = response.url;
191        networkRequest.mimeType = response.mimeType;
192        networkRequest.statusCode = response.status;
193        networkRequest.statusText = response.statusText;
194        networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers);
195        if (response.headersText)
196            networkRequest.responseHeadersText = response.headersText;
197        if (response.requestHeaders)
198            networkRequest.requestHeaders = this._headersMapToHeadersArray(response.requestHeaders);
199        if (response.requestHeadersText)
200            networkRequest.requestHeadersText = response.requestHeadersText;
201
202        networkRequest.connectionReused = response.connectionReused;
203        networkRequest.connectionId = response.connectionId;
204
205        if (response.fromDiskCache)
206            networkRequest.cached = true;
207        else
208            networkRequest.timing = response.timing;
209
210        if (!this._mimeTypeIsConsistentWithType(networkRequest)) {
211            WebInspector.console.addMessage(WebInspector.ConsoleMessage.create(WebInspector.ConsoleMessage.MessageSource.Network,
212                WebInspector.ConsoleMessage.MessageLevel.Warning,
213                WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s: \"%s\".", networkRequest.type.title(), networkRequest.mimeType, networkRequest.url),
214                WebInspector.ConsoleMessage.MessageType.Log,
215                "",
216                0,
217                1,
218                [],
219                null,
220                networkRequest));
221        }
222    },
223
224    /**
225     * @param {WebInspector.NetworkRequest} networkRequest
226     * @return {boolean}
227     */
228    _mimeTypeIsConsistentWithType: function(networkRequest)
229    {
230        // If status is an error, content is likely to be of an inconsistent type,
231        // as it's going to be an error message. We do not want to emit a warning
232        // for this, though, as this will already be reported as resource loading failure.
233        // Also, if a URL like http://localhost/wiki/load.php?debug=true&lang=en produces text/css and gets reloaded,
234        // it is 304 Not Modified and its guessed mime-type is text/php, which is wrong.
235        // Don't check for mime-types in 304-resources.
236        if (networkRequest.hasErrorStatusCode() || networkRequest.statusCode === 304)
237            return true;
238
239        if (typeof networkRequest.type === "undefined"
240            || networkRequest.type === WebInspector.resourceTypes.Other
241            || networkRequest.type === WebInspector.resourceTypes.XHR
242            || networkRequest.type === WebInspector.resourceTypes.WebSocket)
243            return true;
244
245        if (!networkRequest.mimeType)
246            return true; // Might be not known for cached resources with null responses.
247
248        if (networkRequest.mimeType in WebInspector.NetworkManager._MIMETypes)
249            return networkRequest.type.name() in WebInspector.NetworkManager._MIMETypes[networkRequest.mimeType];
250
251        return false;
252    },
253
254    /**
255     * @param {WebInspector.NetworkRequest} networkRequest
256     * @param {?NetworkAgent.CachedResource} cachedResource
257     */
258    _updateNetworkRequestWithCachedResource: function(networkRequest, cachedResource)
259    {
260        networkRequest.type = WebInspector.resourceTypes[cachedResource.type];
261        networkRequest.resourceSize = cachedResource.bodySize;
262        this._updateNetworkRequestWithResponse(networkRequest, cachedResource.response);
263    },
264
265    /**
266     * @param {NetworkAgent.Response} response
267     * @return {boolean}
268     */
269    _isNull: function(response)
270    {
271        if (!response)
272            return true;
273        return !response.status && !response.mimeType && (!response.headers || !Object.keys(response.headers).length);
274    },
275
276    /**
277     * @param {NetworkAgent.RequestId} requestId
278     * @param {NetworkAgent.FrameId} frameId
279     * @param {NetworkAgent.LoaderId} loaderId
280     * @param {string} documentURL
281     * @param {NetworkAgent.Request} request
282     * @param {NetworkAgent.Timestamp} time
283     * @param {NetworkAgent.Initiator} initiator
284     * @param {NetworkAgent.Response=} redirectResponse
285     */
286    requestWillBeSent: function(requestId, frameId, loaderId, documentURL, request, time, initiator, redirectResponse)
287    {
288        var networkRequest = this._inflightRequestsById[requestId];
289        if (networkRequest) {
290            // FIXME: move this check to the backend.
291            if (!redirectResponse)
292                return;
293            this.responseReceived(requestId, frameId, loaderId, time, "Other", redirectResponse);
294            networkRequest = this._appendRedirect(requestId, time, request.url);
295        } else
296            networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, request.url, documentURL, initiator);
297        networkRequest.hasNetworkData = true;
298        this._updateNetworkRequestWithRequest(networkRequest, request);
299        networkRequest.startTime = time;
300
301        this._startNetworkRequest(networkRequest);
302    },
303
304    /**
305     * @param {NetworkAgent.RequestId} requestId
306     */
307    requestServedFromCache: function(requestId)
308    {
309        var networkRequest = this._inflightRequestsById[requestId];
310        if (!networkRequest)
311            return;
312
313        networkRequest.cached = true;
314    },
315
316    /**
317     * @param {NetworkAgent.RequestId} requestId
318     * @param {NetworkAgent.FrameId} frameId
319     * @param {NetworkAgent.LoaderId} loaderId
320     * @param {NetworkAgent.Timestamp} time
321     * @param {PageAgent.ResourceType} resourceType
322     * @param {NetworkAgent.Response} response
323     */
324    responseReceived: function(requestId, frameId, loaderId, time, resourceType, response)
325    {
326        // FIXME: move this check to the backend.
327        if (this._isNull(response))
328            return;
329
330        var networkRequest = this._inflightRequestsById[requestId];
331        if (!networkRequest) {
332            // We missed the requestWillBeSent.
333            var eventData = {};
334            eventData.url = response.url;
335            eventData.frameId = frameId;
336            eventData.loaderId = loaderId;
337            eventData.resourceType = resourceType;
338            eventData.mimeType = response.mimeType;
339            this._manager.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdateDropped, eventData);
340            return;
341        }
342
343        networkRequest.responseReceivedTime = time;
344        networkRequest.type = WebInspector.resourceTypes[resourceType];
345
346        this._updateNetworkRequestWithResponse(networkRequest, response);
347
348        this._updateNetworkRequest(networkRequest);
349    },
350
351    /**
352     * @param {NetworkAgent.RequestId} requestId
353     * @param {NetworkAgent.Timestamp} time
354     * @param {number} dataLength
355     * @param {number} encodedDataLength
356     */
357    dataReceived: function(requestId, time, dataLength, encodedDataLength)
358    {
359        var networkRequest = this._inflightRequestsById[requestId];
360        if (!networkRequest)
361            return;
362
363        networkRequest.resourceSize += dataLength;
364        if (encodedDataLength != -1)
365            networkRequest.increaseTransferSize(encodedDataLength);
366        networkRequest.endTime = time;
367
368        this._updateNetworkRequest(networkRequest);
369    },
370
371    /**
372     * @param {NetworkAgent.RequestId} requestId
373     * @param {NetworkAgent.Timestamp} finishTime
374     */
375    loadingFinished: function(requestId, finishTime)
376    {
377        var networkRequest = this._inflightRequestsById[requestId];
378        if (!networkRequest)
379            return;
380        this._finishNetworkRequest(networkRequest, finishTime);
381    },
382
383    /**
384     * @param {NetworkAgent.RequestId} requestId
385     * @param {NetworkAgent.Timestamp} time
386     * @param {string} localizedDescription
387     * @param {boolean=} canceled
388     */
389    loadingFailed: function(requestId, time, localizedDescription, canceled)
390    {
391        var networkRequest = this._inflightRequestsById[requestId];
392        if (!networkRequest)
393            return;
394
395        networkRequest.failed = true;
396        networkRequest.canceled = canceled;
397        networkRequest.localizedFailDescription = localizedDescription;
398        this._finishNetworkRequest(networkRequest, time);
399    },
400
401    /**
402     * @param {NetworkAgent.RequestId} requestId
403     * @param {NetworkAgent.FrameId} frameId
404     * @param {NetworkAgent.LoaderId} loaderId
405     * @param {string} documentURL
406     * @param {NetworkAgent.Timestamp} time
407     * @param {NetworkAgent.Initiator} initiator
408     * @param {NetworkAgent.CachedResource} cachedResource
409     */
410    requestServedFromMemoryCache: function(requestId, frameId, loaderId, documentURL, time, initiator, cachedResource)
411    {
412        var networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, cachedResource.url, documentURL, initiator);
413        this._updateNetworkRequestWithCachedResource(networkRequest, cachedResource);
414        networkRequest.cached = true;
415        networkRequest.requestMethod = "GET";
416        this._startNetworkRequest(networkRequest);
417        networkRequest.startTime = networkRequest.responseReceivedTime = time;
418        this._finishNetworkRequest(networkRequest, time);
419    },
420
421    /**
422     * @param {NetworkAgent.RequestId} requestId
423     * @param {string} requestURL
424     */
425    webSocketCreated: function(requestId, requestURL)
426    {
427        var networkRequest = new WebInspector.NetworkRequest(requestId, requestURL, "", "", "");
428        networkRequest.type = WebInspector.resourceTypes.WebSocket;
429        this._startNetworkRequest(networkRequest);
430    },
431
432    /**
433     * @param {NetworkAgent.RequestId} requestId
434     * @param {NetworkAgent.Timestamp} time
435     * @param {NetworkAgent.WebSocketRequest} request
436     */
437    webSocketWillSendHandshakeRequest: function(requestId, time, request)
438    {
439        var networkRequest = this._inflightRequestsById[requestId];
440        if (!networkRequest)
441            return;
442
443        networkRequest.requestMethod = "GET";
444        networkRequest.requestHeaders = this._headersMapToHeadersArray(request.headers);
445        networkRequest.webSocketRequestKey3 = request.requestKey3;
446        networkRequest.startTime = time;
447
448        this._updateNetworkRequest(networkRequest);
449    },
450
451    /**
452     * @param {NetworkAgent.RequestId} requestId
453     * @param {NetworkAgent.Timestamp} time
454     * @param {NetworkAgent.WebSocketResponse} response
455     */
456    webSocketHandshakeResponseReceived: function(requestId, time, response)
457    {
458        var networkRequest = this._inflightRequestsById[requestId];
459        if (!networkRequest)
460            return;
461
462        networkRequest.statusCode = response.status;
463        networkRequest.statusText = response.statusText;
464        networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers);
465        networkRequest.webSocketChallengeResponse = response.challengeResponse;
466        networkRequest.responseReceivedTime = time;
467
468        this._updateNetworkRequest(networkRequest);
469    },
470
471    /**
472     * @param {NetworkAgent.RequestId} requestId
473     * @param {NetworkAgent.Timestamp} time
474     * @param {NetworkAgent.WebSocketFrame} response
475     */
476    webSocketFrameReceived: function(requestId, time, response)
477    {
478        var networkRequest = this._inflightRequestsById[requestId];
479        if (!networkRequest)
480            return;
481
482        networkRequest.addFrame(response, time);
483        networkRequest.responseReceivedTime = time;
484
485        this._updateNetworkRequest(networkRequest);
486    },
487
488    /**
489     * @param {NetworkAgent.RequestId} requestId
490     * @param {NetworkAgent.Timestamp} time
491     * @param {NetworkAgent.WebSocketFrame} response
492     */
493    webSocketFrameSent: function(requestId, time, response)
494    {
495        var networkRequest = this._inflightRequestsById[requestId];
496        if (!networkRequest)
497            return;
498
499        networkRequest.addFrame(response, time, true);
500        networkRequest.responseReceivedTime = time;
501
502        this._updateNetworkRequest(networkRequest);
503    },
504
505    /**
506     * @param {NetworkAgent.RequestId} requestId
507     * @param {NetworkAgent.Timestamp} time
508     * @param {string} errorMessage
509     */
510    webSocketFrameError: function(requestId, time, errorMessage)
511    {
512        var networkRequest = this._inflightRequestsById[requestId];
513        if (!networkRequest)
514            return;
515
516        networkRequest.addFrameError(errorMessage, time);
517        networkRequest.responseReceivedTime = time;
518
519        this._updateNetworkRequest(networkRequest);
520    },
521
522    /**
523     * @param {NetworkAgent.RequestId} requestId
524     * @param {NetworkAgent.Timestamp} time
525     */
526    webSocketClosed: function(requestId, time)
527    {
528        var networkRequest = this._inflightRequestsById[requestId];
529        if (!networkRequest)
530            return;
531        this._finishNetworkRequest(networkRequest, time);
532    },
533
534    /**
535     * @param {NetworkAgent.RequestId} requestId
536     * @param {NetworkAgent.Timestamp} time
537     * @param {string} redirectURL
538     * @return {WebInspector.NetworkRequest}
539     */
540    _appendRedirect: function(requestId, time, redirectURL)
541    {
542        var originalNetworkRequest = this._inflightRequestsById[requestId];
543        var previousRedirects = originalNetworkRequest.redirects || [];
544        originalNetworkRequest.requestId = "redirected:" + requestId + "." + previousRedirects.length;
545        delete originalNetworkRequest.redirects;
546        if (previousRedirects.length > 0)
547            originalNetworkRequest.redirectSource = previousRedirects[previousRedirects.length - 1];
548        this._finishNetworkRequest(originalNetworkRequest, time);
549        var newNetworkRequest = this._createNetworkRequest(requestId, originalNetworkRequest.frameId, originalNetworkRequest.loaderId,
550             redirectURL, originalNetworkRequest.documentURL, originalNetworkRequest.initiator);
551        newNetworkRequest.redirects = previousRedirects.concat(originalNetworkRequest);
552        return newNetworkRequest;
553    },
554
555    /**
556     * @param {WebInspector.NetworkRequest} networkRequest
557     */
558    _startNetworkRequest: function(networkRequest)
559    {
560        this._inflightRequestsById[networkRequest.requestId] = networkRequest;
561        this._inflightRequestsByURL[networkRequest.url] = networkRequest;
562        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestStarted, networkRequest);
563    },
564
565    /**
566     * @param {WebInspector.NetworkRequest} networkRequest
567     */
568    _updateNetworkRequest: function(networkRequest)
569    {
570        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdated, networkRequest);
571    },
572
573    /**
574     * @param {WebInspector.NetworkRequest} networkRequest
575     * @param {NetworkAgent.Timestamp} finishTime
576     */
577    _finishNetworkRequest: function(networkRequest, finishTime)
578    {
579        networkRequest.endTime = finishTime;
580        networkRequest.finished = true;
581        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestFinished, networkRequest);
582        delete this._inflightRequestsById[networkRequest.requestId];
583        delete this._inflightRequestsByURL[networkRequest.url];
584    },
585
586    /**
587     * @param {string} eventType
588     * @param {WebInspector.NetworkRequest} networkRequest
589     */
590    _dispatchEventToListeners: function(eventType, networkRequest)
591    {
592        this._manager.dispatchEventToListeners(eventType, networkRequest);
593    },
594
595    /**
596     * @param {NetworkAgent.RequestId} requestId
597     * @param {string} frameId
598     * @param {NetworkAgent.LoaderId} loaderId
599     * @param {string} url
600     * @param {string} documentURL
601     * @param {NetworkAgent.Initiator} initiator
602     */
603    _createNetworkRequest: function(requestId, frameId, loaderId, url, documentURL, initiator)
604    {
605        var networkRequest = new WebInspector.NetworkRequest(requestId, url, documentURL, frameId, loaderId);
606        networkRequest.initiator = initiator;
607        return networkRequest;
608    }
609}
610
611/**
612 * @type {?WebInspector.NetworkManager}
613 */
614WebInspector.networkManager = null;
615
Full Screen

Proxy.js

Source: Proxy.js Github

copy
1describe("Ext.data.soap.Proxy", function() {
2    var proxy;
3
4    function makeProxy(config) {
5        proxy = new Ext.data.soap.Proxy(Ext.apply({
6            model: 'spec.Foo',
7            type: 'soap',
8            url: '/soapUrl',
9            api: {
10                create: 'Create',
11                read: 'Read',
12                update: 'Update',
13                destroy: 'Destroy'
14            },
15            soapAction: {
16                create: 'CreateAction',
17                read: 'ReadAction',
18                update: 'UpdateAction',
19                destroy: 'DestroyAction'
20            },
21            operationParam: 'operation',
22            targetNamespace: 'tns'
23        }, config || {}));
24    }
25
26    beforeEach(function() {
27        Ext.ClassManager.enableNamespaceParseCache = false; 
28        Ext.define('spec.Foo', {
29            extend: 'Ext.data.Model',
30            fields: [
31                { name: 'id', type: 'int' },
32                { name: 'bar', type: 'string' }
33            ]
34        });
35    });
36    
37    afterEach(function(){
38        Ext.ClassManager.enableNamespaceParseCache = true; 
39        Ext.ModelManager.types = {};
40        Ext.undefine('spec.Foo');
41    });
42
43    describe("construction", function() {
44        beforeEach(function() {
45            makeProxy();
46        });
47        it("should create a soap reader", function() {
48            expect(proxy.reader instanceof Ext.data.soap.Reader).toBe(true);
49        });
50    });
51
52    describe("doRequest", function() {
53        var operation, callback, createdCallback, scope, request;
54
55        function makeRequest(action, proxyConfig, requestParams) {
56            makeProxy(proxyConfig);
57            callback = function() {};
58            createdCallback = function() {};
59            scope = {};
60
61            spyOn(Ext.Ajax, 'request');
62            spyOn(proxy, 'createRequestCallback').andReturn(createdCallback);
63
64            operation = new Ext.data.Operation({ action: action });
65
66            if (action !== 'read') {
67                operation.records = [
68                    new spec.Foo({id: 1, bar: 'abc'}),
69                    new spec.Foo({id: 2, bar: 'xyz'})
70                ]
71            }
72            if (requestParams) {
73                operation.params = requestParams;
74            }
75            request = proxy.doRequest(operation, callback, scope);
76        }
77
78        describe("read operation", function() {
79            it("should construct a request object", function() {
80                makeRequest('read');
81                expect(request instanceof Ext.data.Request).toBe(true);
82            });
83
84            it("should pass the request object to Ext.Ajax.request", function() {
85                makeRequest('read');
86                expect(Ext.Ajax.request).toHaveBeenCalledWith(request);
87            });
88
89            it("should set the url in the request object and append the operationParam to the url", function() {
90                makeRequest('read');
91                expect(request.url).toBe('/soapUrl?operation=Read');
92            });
93
94            it("should do an HTTP POST", function() {
95                makeRequest('read');
96                expect(request.method).toBe('POST');
97            });
98
99            it("should set the action in the request object", function() {
100                makeRequest('read');
101                expect(request.action).toBe('read');
102            });
103
104            it("should not set request parameters", function() {
105                makeRequest('read');
106                expect(request.params).toBeUndefined();
107            });
108
109            it("should set the SOAPAction header in the request", function() {
110                makeRequest('read');
111                expect(request.headers.SOAPAction).toBe('ReadAction');
112            });
113
114            it("should allow the addition of extra request headers", function() {
115                makeRequest('read', {
116                    headers: {
117                        wibble: 'wobble'
118                    }
119                });
120                expect(request.headers.SOAPAction).toBe('ReadAction');
121                expect(request.headers.wibble).toBe('wobble');
122            });
123
124            it("should create a request callback request object", function() {
125                makeRequest('read');
126                expect(proxy.createRequestCallback).toHaveBeenCalledWith(request, operation, callback, scope);
127            });
128
129            it("should set the request callback in the request object", function() {
130                makeRequest('read');
131                expect(request.callback).toBe(createdCallback);
132            });
133
134            it("should encode the parameters into a soap envelope", function() {
135                makeRequest('read', null, {
136                    foo: 42,
137                    bar: 'abc'
138                });
139                expect(request.xmlData).toBe([
140                    '<?xml version="1.0" encoding="utf-8" ?>',
141                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
142                        '<soap:Body>',
143                            '<Read xmlns="tns">',
144                                '<foo>42</foo>',
145                                '<bar>abc</bar>',
146                            '</Read>',
147                        '</soap:Body>',
148                    '</soap:Envelope>'
149                ].join(''));
150            });
151
152            it("should have a soap envelope with empty operation element if there are no paremeters", function() {
153                makeRequest('read');
154                expect(request.xmlData).toBe([
155                    '<?xml version="1.0" encoding="utf-8" ?>',
156                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
157                        '<soap:Body>',
158                            '<Read xmlns="tns">',
159                            '</Read>',
160                        '</soap:Body>',
161                    '</soap:Envelope>'
162                ].join(''));
163            });
164
165            it("should merge extraParams into params before creating the soap envelope", function() {
166                makeRequest('read', {
167                    extraParams: {
168                        baz: 9000
169                    }
170                }, {
171                    foo: 42,
172                    bar: 'abc'
173                });
174                expect(request.xmlData).toBe([
175                    '<?xml version="1.0" encoding="utf-8" ?>',
176                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
177                        '<soap:Body>',
178                            '<Read xmlns="tns">',
179                                '<foo>42</foo>',
180                                '<bar>abc</bar>',
181                                '<baz>9000</baz>',
182                            '</Read>',
183                        '</soap:Body>',
184                    '</soap:Envelope>'
185                ].join(''));
186            });
187
188            it("should give params precedence over extraParams if there is a conflict", function() {
189                makeRequest('read', {
190                    extraParams: {
191                        baz: 9000,
192                        bar: 'xyz'
193                    }
194                }, {
195                    foo: 42,
196                    bar: 'abc'
197                });
198                expect(request.xmlData).toBe([
199                    '<?xml version="1.0" encoding="utf-8" ?>',
200                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
201                        '<soap:Body>',
202                            '<Read xmlns="tns">',
203                                '<foo>42</foo>',
204                                '<bar>abc</bar>',
205                                '<baz>9000</baz>',
206                            '</Read>',
207                        '</soap:Body>',
208                    '</soap:Envelope>'
209                ].join(''));
210            });
211
212            it("should allow configuration of a custom envelope template", function() {
213                makeRequest('read', {
214                    envelopeTpl: [
215                        '<?xml version="1.0" encoding="utf-8" ?>',
216                        '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
217                            'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
218                            '{[values.bodyTpl.apply(values)]}',
219                        '</soap:Envelope>'
220                    ]
221                }, {
222                    foo: 42
223                });
224                expect(request.xmlData).toBe([
225                    '<?xml version="1.0" encoding="utf-8" ?>',
226                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
227                        'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
228                        '<soap:Body>',
229                            '<Read xmlns="tns">',
230                                '<foo>42</foo>',
231                            '</Read>',
232                        '</soap:Body>',
233                    '</soap:Envelope>'
234                ].join(''));
235            });
236
237            it("should allow configuration of a custom body template", function() {
238                makeRequest('read', {
239                    readBodyTpl: [
240                        '<soap:Body>',
241                            '<RequestContainer>',
242                                '<{operation} xmlns="{targetNamespace}">',
243                                    '<tpl foreach="params">',
244                                        '<{$}>{.}</{$}>',
245                                    '</tpl>',
246                                '</{operation}>',
247                            '</RequestContainer>',
248                        '</soap:Body>'
249                    ]
250                }, {
251                    foo: 42
252                });
253                expect(request.xmlData).toBe([
254                    '<?xml version="1.0" encoding="utf-8" ?>',
255                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
256                        '<soap:Body>',
257                            '<RequestContainer>',
258                                '<Read xmlns="tns">',
259                                    '<foo>42</foo>',
260                                '</Read>',
261                            '</RequestContainer>',
262                        '</soap:Body>',
263                    '</soap:Envelope>'
264                ].join(''));
265            });
266        });
267
268        describe("create operation", function() {
269            it("should construct a request object", function() {
270                makeRequest('create');
271                expect(request instanceof Ext.data.Request).toBe(true);
272            });
273
274            it("should pass the request object to Ext.Ajax.request", function() {
275                makeRequest('create');
276                expect(Ext.Ajax.request).toHaveBeenCalledWith(request);
277            });
278
279            it("should set the url in the request object and append the operationParam to the url", function() {
280                makeRequest('create');
281                expect(request.url).toBe('/soapUrl?operation=Create');
282            });
283
284            it("should do an HTTP POST", function() {
285                makeRequest('create');
286                expect(request.method).toBe('POST');
287            });
288
289            it("should set the action in the request object", function() {
290                makeRequest('create');
291                expect(request.action).toBe('create');
292            });
293
294            it("should not set request parameters", function() {
295                makeRequest('create');
296                expect(request.params).toBeUndefined();
297            });
298
299            it("should set the SOAPAction header in the request", function() {
300                makeRequest('create');
301                expect(request.headers.SOAPAction).toBe('CreateAction');
302            });
303
304            it("should allow the addition of extra request headers", function() {
305                makeRequest('create', {
306                    headers: {
307                        wibble: 'wobble'
308                    }
309                });
310                expect(request.headers.SOAPAction).toBe('CreateAction');
311                expect(request.headers.wibble).toBe('wobble');
312            });
313
314            it("should create a request callback request object", function() {
315                makeRequest('create');
316                expect(proxy.createRequestCallback).toHaveBeenCalledWith(request, operation, callback, scope);
317            });
318
319            it("should set the request callback in the request object", function() {
320                makeRequest('create');
321                expect(request.callback).toBe(createdCallback);
322            });
323
324            it("should encode the records into a soap envelope", function() {
325                makeRequest('create');
326                expect(request.xmlData).toBe([
327                    '<?xml version="1.0" encoding="utf-8" ?>',
328                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
329                        '<soap:Body>',
330                            '<Create xmlns="tns">',
331                                '<Foo>',
332                                    '<id>1</id>',
333                                    '<bar>abc</bar>',
334                                '</Foo>',
335                                '<Foo>',
336                                    '<id>2</id>',
337                                    '<bar>xyz</bar>',
338                                '</Foo>',
339                            '</Create>',
340                        '</soap:Body>',
341                    '</soap:Envelope>'
342                ].join(''));
343            });
344
345            it("should allow configuration of a custom envelope template", function() {
346                makeRequest('create', {
347                    envelopeTpl: [
348                        '<?xml version="1.0" encoding="utf-8" ?>',
349                        '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
350                            'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
351                            '{[values.bodyTpl.apply(values)]}',
352                        '</soap:Envelope>'
353                    ]
354                });
355                expect(request.xmlData).toBe([
356                    '<?xml version="1.0" encoding="utf-8" ?>',
357                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ',
358                        'xmlns:xsd= "http://www.w3.org/2001/XMLSchema">',
359                        '<soap:Body>',
360                            '<Create xmlns="tns">',
361                                '<Foo>',
362                                    '<id>1</id>',
363                                    '<bar>abc</bar>',
364                                '</Foo>',
365                                '<Foo>',
366                                    '<id>2</id>',
367                                    '<bar>xyz</bar>',
368                                '</Foo>',
369                            '</Create>',
370                        '</soap:Body>',
371                    '</soap:Envelope>'
372                ].join(''));
373            });
374
375            it("should allow configuration of a custom body template", function() {
376                makeRequest('create', {
377                    createBodyTpl: [
378                        '<soap:Body>',
379                            '<RequestContainer>',
380                                '<{operation} xmlns="{targetNamespace}">',
381                                    '<tpl for="records">',
382                                        '{% var recordName=values.modelName.split(".").pop(); %}',
383                                        '<{[recordName]}>',
384                                            '<tpl for="fields">',
385                                                '<{name}>{[parent.get(values.name)]}</{name}>',
386                                            '</tpl>',
387                                        '</{[recordName]}>',
388                                    '</tpl>',
389                                '</{operation}>',
390                            '</RequestContainer>',
391                        '</soap:Body>'
392                    ]
393                });
394                expect(request.xmlData).toBe([
395                    '<?xml version="1.0" encoding="utf-8" ?>',
396                    '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
397                        '<soap:Body>',
398                            '<RequestContainer>',
399                                '<Create xmlns="tns">',
400                                    '<Foo>',
401                                        '<id>1</id>',
402                                        '<bar>abc</bar>',
403                                    '</Foo>',
404                                    '<Foo>',
405                                        '<id>2</id>',
406                                        '<bar>xyz</bar>',
407                                    '</Foo>',
408                                '</Create>',
409                            '</RequestContainer>',
410                        '</soap:Body>',
411                    '</soap:Envelope>'
412                ].join(''));
413            });
414        });
415
416        describe("update operation", function() {
417            it("should construct a request object", function() {
418                makeRequest('update');
419                expect(request instanceof Ext.data.Request).toBe(true);
420            });
421
422            it("should pass the request object to Ext.Ajax.request", function() {
423                makeRequest('update');
424                expect(Ext.Ajax.request).toHaveBeenCalledWith(request);
425            });
426
427            it("should set the url in the request object and append the operationParam to the url", function() {
428                makeRequest('update');
429                expect(request.url).toBe('/soapUrl?operation=Update');
430            });
431
432            it("should do an HTTP POST", function() {
433                makeRequest('update');
434                expect(request.method).toBe('POST');
435            });
436
437            it("should set the action in the request object", function() {
438                makeRequest('update');
439                expect(request.action).toBe('update');
440            });
441
442            it("should not set request parameters", function() {
443                makeRequest('update');
444                expect(request.params).toBeUndefined();
445            });
446
447            it("should set the SOAPAction header in the request", function() {
448                makeRequest('update');
449                expect(request.headers.SOAPAction).toBe('UpdateAction');
450            });
451
452            it("should allow the addition of extra request headers", function() {
453                makeRequest('update', {
454                    headers: {
455                        wibble: 'wobble'
456                    }
457                });
458<