How to use json method in storybook-root

Best JavaScript code snippet using storybook-root

views.py

Source:views.py Github

copy

Full Screen

1from django.http import HttpResponse, JsonResponse2from django.shortcuts import render, get_object_or_4043from django.views.generic import View4from django.core.exceptions import ValidationError5from django.contrib.auth import hashers6from django.views.decorators.csrf import csrf_exempt7from django.utils.decorators import method_decorator8from datetime import datetime, timezone9import json10from fafs_api.models import User, Address, School, Category, Product, Transaction, Authenticator11def get_key(dictionary, key):12 try:13 return dictionary[key]14 except KeyError:15 return None16def retrieve_all_fields(dictionary, field_list):17 return_dict = {}18 for field in field_list:19 value = get_key(dictionary, field)20 return_dict[field] = value21 return return_dict22def get_object_or_none(model, **kwargs):23 try:24 return model.objects.get(**kwargs)25 except model.DoesNotExist:26 return None27def json_encode_dict_and_status(dictionary, status):28 response_dict = {}29 response_dict["status"] = status30 response_dict["response"] = dictionary31 return response_dict32class AuthView(View):33 model = Authenticator34 required_fields = ['user_id']35 @method_decorator(csrf_exempt)36 def dispatch(self, request, *args, **kwargs):37 return super(AuthView, self).dispatch(request, *args, **kwargs)38 def get(self, request, token=None):39 status = False40 if token is not None:41 queryset = get_object_or_none(42 self.model,43 token=token44 )45 if queryset is not None:46 status = True47 json_data = {48 "token": queryset.token,49 "user_id":queryset.user.pk,50 "date_created":queryset.date_created51 }52 else:53 status = False54 json_data = {"message": "No authenticator with token found"}55 else:56 status = True57 queryset = self.model.objects.all()58 json_data = list(queryset.values('token', 'user_id', 'date_created'))59 return JsonResponse(json_encode_dict_and_status(json_data, status))60 def post(self, request):61 json_data = json.loads(request.body.decode('utf-8'))62 field_dict = retrieve_all_fields(63 json_data,64 self.required_fields65 )66 try:67 user = User.objects.get(pk=field_dict['user_id'])68 auth = Authenticator()69 auth.user = user70 auth.save()71 response_data = {72 "token": auth.token,73 "user_id": auth.user.pk,74 "date_created": auth.date_created75 }76 status = True77 except User.DoesNotExist:78 status = False79 response_data = {"message": "Invalid user id"}80 return JsonResponse(json_encode_dict_and_status(response_data, status))81 def delete(self, request, token=None):82 status = False83 obj = get_object_or_none(self.model, token=token)84 if obj is not None:85 obj.delete()86 status = True87 return JsonResponse(json_encode_dict_and_status({},status))88@method_decorator(csrf_exempt)89def auth_check(request):90 required_fields = ['authenticator']91 if request.method == "POST":92 json_data = json.loads(request.body.decode('utf-8'))93 field_dict = retrieve_all_fields(94 json_data,95 required_fields96 )97 status = False98 try:99 auth = Authenticator.objects.get(token=field_dict['authenticator'])100 user_id = auth.user.pk101 status = True102 response_data = {"user_id": user_id}103 except Authenticator.DoesNotExist:104 response_data = {"message": "Invalid authenticator"}105 return JsonResponse(json_encode_dict_and_status(response_data, status))106@method_decorator(csrf_exempt)107def users_check_pass(request):108 required_fields = ['email', 'password']109 if request.method == "POST":110 json_data = json.loads(request.body.decode('utf-8'))111 field_dict = retrieve_all_fields(112 json_data,113 required_fields114 )115 status = False116 response_data = {"message": "Incorrect email/password"}117 try:118 login_user = User.objects.get(email=field_dict['email'])119 # Check password120 hashed_password = login_user.password121 if hashers.check_password(field_dict['password'], hashed_password):122 status = True123 response_data = {"user_id": login_user.pk}124 except User.DoesNotExist:125 pass126 return JsonResponse(json_encode_dict_and_status(response_data, status))127class UserView(View):128 required_fields = ['email', 'school_id', 'password']129 update_fields = ['user_pk','email','password']130 model = User131 @method_decorator(csrf_exempt)132 def dispatch(self, request, *args, **kwargs):133 return super(UserView, self).dispatch(request, *args, **kwargs)134 def get(self, request, pk=None):135 status = False136 if pk is not None:137 queryset = get_object_or_none(138 self.model,139 pk=pk140 )141 if queryset is not None:142 status = True143 json_data = {144 "pk":queryset.pk,145 "email":queryset.email,146 "school_id":queryset.school_id.pk,147 "password":queryset.password148 }149 else:150 status = False151 json_data = {}152 else:153 status = True154 queryset = self.model.objects.all()155 json_data = list(queryset.values('pk','email','school_id', 'password'))156 return JsonResponse(json_encode_dict_and_status(json_data, status))157 def post(self, request):158 status = True159 json_data = json.loads(request.body.decode('utf-8'))160 field_dict = retrieve_all_fields(161 json_data,162 self.required_fields163 )164 try:165 user = self.model.objects.create_user(166 email=field_dict['email'],167 password=field_dict['password'],168 school=field_dict['school_id']169 )170 json_data = {171 "pk":user.pk,172 "email":user.email,173 "school_id":user.school_id.pk174 }175 except ValidationError as e:176 json_data = e.message_dict177 status = False178 return JsonResponse(json_encode_dict_and_status(json_data, status))179 def patch(self, request):180 status = True181 json_data = json.loads(request.body.decode('utf-8'))182 field_dict = retrieve_all_fields(183 json_data,184 self.update_fields185 )186 try:187 user = self.model.objects.update_user(188 user_pk = get_key(field_dict,'user_pk'),189 email = get_key(field_dict,'email'),190 password = get_key(field_dict,'password')191 )192 json_data = {193 "pk":user.pk,194 "email":user.email,195 "school_id":user.school_id.pk196 }197 except ValidationError as e:198 json_data = e.message_dict199 status = False200 return JsonResponse(json_encode_dict_and_status(json_data, status))201 def delete(self, request, pk=None):202 status = False203 obj = get_object_or_none(self.model, pk=pk)204 if obj is not None:205 obj.delete()206 status = True207 return JsonResponse(json_encode_dict_and_status({},status))208class AddressView(View):209 required_fields = ['street_number', 'street_name', 'city', 'state', 'zipcode', 'description']210 model = Address211 @method_decorator(csrf_exempt)212 def dispatch(self, request, *args, **kwargs):213 return super(AddressView, self).dispatch(request, *args, **kwargs)214 def get(self, request, pk=None):215 status = True216 if pk is not None:217 queryset = get_object_or_none(218 self.model,219 pk=pk220 )221 if queryset is not None:222 json_data = {223 "pk": queryset.pk,224 "street_number": queryset.street_number,225 "street_name": queryset.street_name,226 "city": queryset.city,227 "state": queryset.state,228 "zipcode": queryset.zipcode,229 "description": queryset.description,230 "address_2": queryset.address_2231 }232 else:233 status = False234 json_data = {}235 else:236 queryset = self.model.objects.all()237 json_data = list(queryset.values('pk', 'street_number', 'street_name',238 'city', 'state', 'zipcode', 'address_2'))239 return JsonResponse(json_encode_dict_and_status(json_data, status))240 def post(self, request):241 status = True242 json_data = json.loads(request.body.decode('utf-8'))243 field_dict = retrieve_all_fields(244 json_data,245 self.required_fields246 )247 try:248 address = self.model(249 street_number = field_dict['street_number'],250 street_name = field_dict['street_name'],251 city = field_dict['city'],252 state = field_dict['state'],253 zipcode = field_dict['zipcode'],254 address_2 = field_dict['address_2']255 )256 address.clean()257 address.save()258 json_data = {259 "street_number": address.street_number,260 "street_name": address.street_name,261 "city": address.city,262 "state": address.state,263 "zipcode": address.zipcode,264 "address_2": address.address_2265 }266 except ValidationError as e:267 status = False268 json_data = e.message_dict269 return JsonResponse(json_encode_dict_and_status(json_data, status))270 def delete(self, request, pk=None):271 status = False272 obj = get_object_or_none(self.model, pk=pk)273 if obj is not None:274 obj.delete()275 status = True276 return JsonResponse(json_encode_dict_and_status({},status))277class SchoolView(View):278 required_fields = ['name','city','state']279 model = School280 @method_decorator(csrf_exempt)281 def dispatch(self, request, *args, **kwargs):282 return super(SchoolView, self).dispatch(request, *args, **kwargs)283 def get(self, request, pk=None):284 status = True285 if pk is not None:286 queryset = get_object_or_none(287 self.model,288 pk=pk)289 if queryset is not None:290 json_data = {291 "pk":queryset.pk,292 "name":queryset.name,293 "city":queryset.city,294 "state":queryset.state295 }296 else:297 status = False298 json_data = {}299 else:300 queryset = self.model.objects.all()301 json_data = list(queryset.values('pk','name','city','state'))302 return JsonResponse(json_encode_dict_and_status(json_data, status))303 def post(self, request):304 status = True305 json_data = json.loads(request.body.decode('utf-8'))306 field_dict = retrieve_all_fields(307 json_data,308 self.required_fields309 )310 try:311 school = self.model(312 name=field_dict['name'],313 city=field_dict['city'],314 state=field_dict['state']315 )316 school.clean()317 school.save()318 json_data = {319 "name":school.name,320 "city":school.city,321 "state":school.state,322 "pk":school.pk323 }324 except ValidationError as e:325 status = False326 json_data = e.message_dict327 return JsonResponse(json_encode_dict_and_status(json_data, status))328 def delete(self, request, pk=None):329 status = False330 obj = get_object_or_none(self.model, pk=pk)331 if obj is not None:332 obj.delete()333 status = True334 return JsonResponse(json_encode_dict_and_status({},status))335class CategoryView(View):336 required_fields = ['name', 'description']337 model = Category338 @method_decorator(csrf_exempt)339 def dispatch(self, request, *args, **kwargs):340 return super(CategoryView, self).dispatch(request, *args, **kwargs)341 def get(self, request, pk=None):342 status = True343 if pk is not None:344 queryset = get_object_or_none(345 self.model,346 pk=pk347 )348 if queryset is not None:349 json_data = {350 "pk": queryset.pk,351 "name": queryset.name,352 "description": queryset.description353 }354 else:355 status = False356 json_data = {}357 else:358 queryset = self.model.objects.all()359 json_data = list(queryset.values('pk', 'name', 'description'))360 return JsonResponse(json_encode_dict_and_status(json_data, status))361 def post(self, request):362 status = True363 json_data = json.loads(request.body.decode('utf-8'))364 field_dict = retrieve_all_fields(365 json_data,366 self.required_fields367 )368 try:369 category = self.model(370 name=field_dict['name'],371 description=field_dict['description']372 )373 category.clean()374 category.save()375 json_data = {376 "name": category.name,377 "description": category.description378 }379 except ValidationError as e:380 status = False381 json_data = e.message_dict382 return JsonResponse(json_encode_dict_and_status(json_data, status))383 def delete(self, request, pk=None):384 status = False385 obj = get_object_or_none(self.model, pk=pk)386 if obj is not None:387 obj.delete()388 status = True389 return JsonResponse(json_encode_dict_and_status({},status))390 def delete(self, request, pk=None):391 status = False392 obj = get_object_or_none(self.model, pk=pk)393 if obj is not None:394 obj.delete()395 status = True396 return JsonResponse(json_encode_dict_and_status({},status))397class ProductView(View):398 required_fields = ['name', 'description', 'category_id', 'price', 'owner_id', 'pick_up']399 model = Product400 @method_decorator(csrf_exempt)401 def dispatch(self, request, *args, **kwargs):402 return super(ProductView, self).dispatch(request, *args, **kwargs)403 def get(self, request, pk=None):404 status = True405 if pk is not None:406 queryset = get_object_or_none(407 self.model,408 pk=pk409 )410 if queryset is not None:411 json_data = {412 "pk": queryset.pk,413 "name": queryset.name,414 "description": queryset.description,415 "category_id": queryset.category_id.pk,416 "price": queryset.price,417 "owner_id": queryset.owner_id.pk,418 "pick_up": queryset.pick_up,419 "time_posted": queryset.time_posted,420 "time_updated": queryset.time_updated421 }422 else:423 status = False424 json_data = {}425 else:426 queryset = self.model.objects.all()427 json_data = list(queryset.values('pk','name','description',428 'category_id', 'price', 'owner_id', 'pick_up', 'time_posted', 'time_updated'))429 return JsonResponse(json_encode_dict_and_status(json_data, status))430 def post(self, request):431 status = True432 json_data = json.loads(request.body.decode('utf-8'))433 field_dict = retrieve_all_fields(434 json_data,435 self.required_fields436 )437 try:438 category = None439 owner = None440 try:441 category = Category.objects.get(pk=field_dict['category_id'])442 owner = User.objects.get(pk=field_dict['owner_id'])443 except (Category.DoesNotExist, User.DoesNotExist):444 raise ValidationError({445 "Error":"Invalid category or owner id"446 })447 product = self.model(448 name=field_dict['name'],449 description=field_dict['description'],450 category_id=category,451 price=field_dict['price'],452 owner_id=owner,453 pick_up=field_dict['pick_up']454 )455 product.clean()456 product.save()457 json_data = {458 "pk": product.pk,459 "name": product.name,460 "description": product.description,461 "category_id": product.category_id.pk,462 "price": product.price,463 "owner_id": product.owner_id.pk,464 "pick_up": product.pick_up,465 "time_posted": product.time_posted,466 "time_updated": product.time_updated467 }468 except ValidationError as e:469 status = False470 json_data = e.message_dict471 return JsonResponse(json_encode_dict_and_status(json_data, status))472 def delete(self, request, pk=None):473 status = False474 obj = get_object_or_none(self.model, pk=pk)475 if obj is not None:476 obj.delete()477 status = True478 return JsonResponse(json_encode_dict_and_status({},status))479class TransactionView(View):480 required_fields = ['seller', 'buyer', 'product_id']481 model = Transaction482 @method_decorator(csrf_exempt)483 def dispatch(self, request, *args, **kwargs):484 return super(TransactionView, self).dispatch(request, *args, **kwargs)485 def get(self, request, pk=None):486 status = True487 if pk is not None:488 queryset = get_object_or_none(489 self.model,490 pk=pk491 )492 if queryset is not None:493 json_data = {494 "pk": queryset.pk,495 "seller": queryset.seller.pk,496 "buyer": queryset.buyer.pk,497 "product_id": queryset.product_id.pk498 }499 else:500 status = False501 json_data = {}502 else:503 queryset = self.model.objects.all()504 json_data = list(queryset.values('pk', 'seller', 'buyer', 'product_id'))505 return JsonResponse(json_encode_dict_and_status(json_data, status))506 def post(self, request):507 status = True508 json_data = json.loads(request.body.decode('utf-8'))509 field_dict = retrieve_all_fields(510 json_data,511 self.required_fields512 )513 try:514 seller_id = None515 buyer_id = None516 product_id = None517 try:518 seller_id = User.objects.get(pk=field_dict['seller'])519 buyer_id = User.objects.get(pk=field_dict['buyer'])520 product_id = Product.objects.get(pk=field_dict['product_id'])521 except User.DoesNotExist:522 raise ValidationError({523 "Error":"Invalid seller id"524 })525 transaction = self.model(526 seller=seller_id,527 buyer=buyer_id,528 product_id=product_id529 )530 transaction.clean()531 transaction.save()532 json_data = {533 "seller": transaction.seller.pk,534 "buyer": transaction.buyer.pk,535 "product_id": transaction.product_id.pk536 }537 except ValidationError as e:538 status = False539 json_data = e.message_dict540 return JsonResponse(json_encode_dict_and_status(json_data, status))541 def delete(self, request, pk=None):542 status = False543 obj = get_object_or_none(self.model, pk=pk)544 if obj is not None:545 obj.delete()546 status = True...

Full Screen

Full Screen

interface_rest.py

Source:interface_rest.py Github

copy

Full Screen

1#!/usr/bin/env python32# Copyright (c) 2014-2017 The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test the REST API."""6from test_framework.test_framework import BitcoinTestFramework7from test_framework.util import *8from struct import *9from io import BytesIO10from codecs import encode11import http.client12import urllib.parse13def deser_uint256(f):14 r = 015 for i in range(8):16 t = unpack(b"<I", f.read(4))[0]17 r += t << (i * 32)18 return r19#allows simple http get calls20def http_get_call(host, port, path, response_object = 0):21 conn = http.client.HTTPConnection(host, port)22 conn.request('GET', path)23 if response_object:24 return conn.getresponse()25 return conn.getresponse().read().decode('utf-8')26#allows simple http post calls with a request body27def http_post_call(host, port, path, requestdata = '', response_object = 0):28 conn = http.client.HTTPConnection(host, port)29 conn.request('POST', path, requestdata)30 if response_object:31 return conn.getresponse()32 return conn.getresponse().read()33class RESTTest (BitcoinTestFramework):34 FORMAT_SEPARATOR = "."35 def set_test_params(self):36 self.setup_clean_chain = True37 self.num_nodes = 338 def setup_network(self, split=False):39 super().setup_network()40 connect_nodes_bi(self.nodes, 0, 2)41 def run_test(self):42 url = urllib.parse.urlparse(self.nodes[0].url)43 self.log.info("Mining blocks...")44 self.nodes[0].generate(1)45 self.sync_all()46 self.nodes[2].generate(100)47 self.sync_all()48 assert_equal(self.nodes[0].getbalance(), 50)49 txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)50 self.sync_all()51 self.nodes[2].generate(1)52 self.sync_all()53 bb_hash = self.nodes[0].getbestblockhash()54 assert_equal(self.nodes[1].getbalance(), Decimal("0.1")) #balance now should be 0.1 on node 155 # load the latest 0.1 tx over the REST API56 json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json")57 json_obj = json.loads(json_string)58 vintx = json_obj['vin'][0]['txid'] # get the vin to later check for utxo (should be spent by then)59 # get n of 0.1 outpoint60 n = 061 for vout in json_obj['vout']:62 if vout['value'] == 0.1:63 n = vout['n']64 #######################################65 # GETUTXOS: query an unspent outpoint #66 #######################################67 json_request = '/checkmempool/'+txid+'-'+str(n)68 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')69 json_obj = json.loads(json_string)70 #check chainTip response71 assert_equal(json_obj['chaintipHash'], bb_hash)72 #make sure there is one utxo73 assert_equal(len(json_obj['utxos']), 1)74 assert_equal(json_obj['utxos'][0]['value'], 0.1)75 #################################################76 # GETUTXOS: now query an already spent outpoint #77 #################################################78 json_request = '/checkmempool/'+vintx+'-0'79 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')80 json_obj = json.loads(json_string)81 #check chainTip response82 assert_equal(json_obj['chaintipHash'], bb_hash)83 #make sure there is no utox in the response because this oupoint has been spent84 assert_equal(len(json_obj['utxos']), 0)85 #check bitmap86 assert_equal(json_obj['bitmap'], "0")87 ##################################################88 # GETUTXOS: now check both with the same request #89 ##################################################90 json_request = '/checkmempool/'+txid+'-'+str(n)+'/'+vintx+'-0'91 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')92 json_obj = json.loads(json_string)93 assert_equal(len(json_obj['utxos']), 1)94 assert_equal(json_obj['bitmap'], "10")95 #test binary response96 bb_hash = self.nodes[0].getbestblockhash()97 binaryRequest = b'\x01\x02'98 binaryRequest += hex_str_to_bytes(txid)99 binaryRequest += pack("i", n)100 binaryRequest += hex_str_to_bytes(vintx)101 binaryRequest += pack("i", 0)102 bin_response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', binaryRequest)103 output = BytesIO()104 output.write(bin_response)105 output.seek(0)106 chainHeight = unpack("i", output.read(4))[0]107 hashFromBinResponse = hex(deser_uint256(output))[2:].zfill(64)108 assert_equal(bb_hash, hashFromBinResponse) #check if getutxo's chaintip during calculation was fine109 assert_equal(chainHeight, 102) #chain height must be 102110 ############################111 # GETUTXOS: mempool checks #112 ############################113 # do a tx and don't sync114 txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)115 json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json")116 json_obj = json.loads(json_string)117 vintx = json_obj['vin'][0]['txid'] # get the vin to later check for utxo (should be spent by then)118 # get n of 0.1 outpoint119 n = 0120 for vout in json_obj['vout']:121 if vout['value'] == 0.1:122 n = vout['n']123 json_request = '/'+txid+'-'+str(n)124 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')125 json_obj = json.loads(json_string)126 assert_equal(len(json_obj['utxos']), 0) #there should be an outpoint because it has just added to the mempool127 json_request = '/checkmempool/'+txid+'-'+str(n)128 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')129 json_obj = json.loads(json_string)130 assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because it has just added to the mempool131 #do some invalid requests132 json_request = '{"checkmempool'133 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'json', json_request, True)134 assert_equal(response.status, 400) #must be a 400 because we send an invalid json request135 json_request = '{"checkmempool'136 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True)137 assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request138 response = http_post_call(url.hostname, url.port, '/rest/getutxos/checkmempool'+self.FORMAT_SEPARATOR+'bin', '', True)139 assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request140 #test limits141 json_request = '/checkmempool/'142 for x in range(0, 20):143 json_request += txid+'-'+str(n)+'/'144 json_request = json_request.rstrip("/")145 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)146 assert_equal(response.status, 400) #must be a 400 because we exceeding the limits147 json_request = '/checkmempool/'148 for x in range(0, 15):149 json_request += txid+'-'+str(n)+'/'150 json_request = json_request.rstrip("/")151 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)152 assert_equal(response.status, 200) #must be a 200 because we are within the limits153 self.nodes[0].generate(1) #generate block to not affect upcoming tests154 self.sync_all()155 ################156 # /rest/block/ #157 ################158 # check binary format159 response = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True)160 assert_equal(response.status, 200)161 assert_greater_than(int(response.getheader('content-length')), 80)162 response_str = response.read()163 # compare with block header164 response_header = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True)165 assert_equal(response_header.status, 200)166 assert_equal(int(response_header.getheader('content-length')), 80)167 response_header_str = response_header.read()168 assert_equal(response_str[0:80], response_header_str)169 # check block hex format170 response_hex = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True)171 assert_equal(response_hex.status, 200)172 assert_greater_than(int(response_hex.getheader('content-length')), 160)173 response_hex_str = response_hex.read()174 assert_equal(encode(response_str, "hex_codec")[0:160], response_hex_str[0:160])175 # compare with hex block header176 response_header_hex = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True)177 assert_equal(response_header_hex.status, 200)178 assert_greater_than(int(response_header_hex.getheader('content-length')), 160)179 response_header_hex_str = response_header_hex.read()180 assert_equal(response_hex_str[0:160], response_header_hex_str[0:160])181 assert_equal(encode(response_header_str, "hex_codec")[0:160], response_header_hex_str[0:160])182 # check json format183 block_json_string = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+'json')184 block_json_obj = json.loads(block_json_string)185 assert_equal(block_json_obj['hash'], bb_hash)186 # compare with json block header187 response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)188 assert_equal(response_header_json.status, 200)189 response_header_json_str = response_header_json.read().decode('utf-8')190 json_obj = json.loads(response_header_json_str, parse_float=Decimal)191 assert_equal(len(json_obj), 1) #ensure that there is one header in the json response192 assert_equal(json_obj[0]['hash'], bb_hash) #request/response hash should be the same193 #compare with normal RPC block response194 rpc_block_json = self.nodes[0].getblock(bb_hash)195 assert_equal(json_obj[0]['hash'], rpc_block_json['hash'])196 assert_equal(json_obj[0]['confirmations'], rpc_block_json['confirmations'])197 assert_equal(json_obj[0]['height'], rpc_block_json['height'])198 assert_equal(json_obj[0]['version'], rpc_block_json['version'])199 assert_equal(json_obj[0]['merkleroot'], rpc_block_json['merkleroot'])200 assert_equal(json_obj[0]['time'], rpc_block_json['time'])201 assert_equal(json_obj[0]['nonce'], rpc_block_json['nonce'])202 assert_equal(json_obj[0]['bits'], rpc_block_json['bits'])203 assert_equal(json_obj[0]['difficulty'], rpc_block_json['difficulty'])204 assert_equal(json_obj[0]['chainwork'], rpc_block_json['chainwork'])205 assert_equal(json_obj[0]['previousblockhash'], rpc_block_json['previousblockhash'])206 #see if we can get 5 headers in one response207 self.nodes[1].generate(5)208 self.sync_all()209 response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/5/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)210 assert_equal(response_header_json.status, 200)211 response_header_json_str = response_header_json.read().decode('utf-8')212 json_obj = json.loads(response_header_json_str)213 assert_equal(len(json_obj), 5) #now we should have 5 header objects214 # do tx test215 tx_hash = block_json_obj['tx'][0]['txid']216 json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"json")217 json_obj = json.loads(json_string)218 assert_equal(json_obj['txid'], tx_hash)219 # check hex format response220 hex_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"hex", True)221 assert_equal(hex_string.status, 200)222 assert_greater_than(int(response.getheader('content-length')), 10)223 # check block tx details224 # let's make 3 tx and mine them on node 1225 txs = []226 txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))227 txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))228 txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))229 self.sync_all()230 # check that there are exactly 3 transactions in the TX memory pool before generating the block231 json_string = http_get_call(url.hostname, url.port, '/rest/mempool/info'+self.FORMAT_SEPARATOR+'json')232 json_obj = json.loads(json_string)233 assert_equal(json_obj['size'], 3)234 # the size of the memory pool should be greater than 3x ~100 bytes235 assert_greater_than(json_obj['bytes'], 300)236 # check that there are our submitted transactions in the TX memory pool237 json_string = http_get_call(url.hostname, url.port, '/rest/mempool/contents'+self.FORMAT_SEPARATOR+'json')238 json_obj = json.loads(json_string)239 for tx in txs:240 assert_equal(tx in json_obj, True)241 # now mine the transactions242 newblockhash = self.nodes[1].generate(1)243 self.sync_all()244 #check if the 3 tx show up in the new block245 json_string = http_get_call(url.hostname, url.port, '/rest/block/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')246 json_obj = json.loads(json_string)247 for tx in json_obj['tx']:248 if not 'coinbase' in tx['vin'][0]: #exclude coinbase249 assert_equal(tx['txid'] in txs, True)250 #check the same but without tx details251 json_string = http_get_call(url.hostname, url.port, '/rest/block/notxdetails/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')252 json_obj = json.loads(json_string)253 for tx in txs:254 assert_equal(tx in json_obj['tx'], True)255 #test rest bestblock256 bb_hash = self.nodes[0].getbestblockhash()257 json_string = http_get_call(url.hostname, url.port, '/rest/chaininfo.json')258 json_obj = json.loads(json_string)259 assert_equal(json_obj['bestblockhash'], bb_hash)260if __name__ == '__main__':...

Full Screen

Full Screen

rest.py

Source:rest.py Github

copy

Full Screen

1#!/usr/bin/env python32# Copyright (c) 2014-2016 The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test the REST API."""6from test_framework.test_framework import BitcoinTestFramework7from test_framework.util import *8from struct import *9from io import BytesIO10from codecs import encode11import http.client12import urllib.parse13def deser_uint256(f):14 r = 015 for i in range(8):16 t = unpack(b"<I", f.read(4))[0]17 r += t << (i * 32)18 return r19#allows simple http get calls20def http_get_call(host, port, path, response_object = 0):21 conn = http.client.HTTPConnection(host, port)22 conn.request('GET', path)23 if response_object:24 return conn.getresponse()25 return conn.getresponse().read().decode('utf-8')26#allows simple http post calls with a request body27def http_post_call(host, port, path, requestdata = '', response_object = 0):28 conn = http.client.HTTPConnection(host, port)29 conn.request('POST', path, requestdata)30 if response_object:31 return conn.getresponse()32 return conn.getresponse().read()33class RESTTest (BitcoinTestFramework):34 FORMAT_SEPARATOR = "."35 def set_test_params(self):36 self.setup_clean_chain = True37 self.num_nodes = 338 def setup_network(self, split=False):39 super().setup_network()40 connect_nodes_bi(self.nodes, 0, 2)41 def run_test(self):42 url = urllib.parse.urlparse(self.nodes[0].url)43 self.log.info("Mining blocks...")44 self.nodes[0].generate(1)45 self.sync_all()46 self.nodes[2].generate(100)47 self.sync_all()48 assert_equal(self.nodes[0].getbalance(), 50)49 txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)50 self.sync_all()51 self.nodes[2].generate(1)52 self.sync_all()53 bb_hash = self.nodes[0].getbestblockhash()54 assert_equal(self.nodes[1].getbalance(), Decimal("0.1")) #balance now should be 0.1 on node 155 # load the latest 0.1 tx over the REST API56 json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json")57 json_obj = json.loads(json_string)58 vintx = json_obj['vin'][0]['txid'] # get the vin to later check for utxo (should be spent by then)59 # get n of 0.1 outpoint60 n = 061 for vout in json_obj['vout']:62 if vout['value'] == 0.1:63 n = vout['n']64 #######################################65 # GETUTXOS: query an unspent outpoint #66 #######################################67 json_request = '/checkmempool/'+txid+'-'+str(n)68 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')69 json_obj = json.loads(json_string)70 #check chainTip response71 assert_equal(json_obj['chaintipHash'], bb_hash)72 #make sure there is one utxo73 assert_equal(len(json_obj['utxos']), 1)74 assert_equal(json_obj['utxos'][0]['value'], 0.1)75 #################################################76 # GETUTXOS: now query an already spent outpoint #77 #################################################78 json_request = '/checkmempool/'+vintx+'-0'79 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')80 json_obj = json.loads(json_string)81 #check chainTip response82 assert_equal(json_obj['chaintipHash'], bb_hash)83 #make sure there is no utox in the response because this oupoint has been spent84 assert_equal(len(json_obj['utxos']), 0)85 #check bitmap86 assert_equal(json_obj['bitmap'], "0")87 ##################################################88 # GETUTXOS: now check both with the same request #89 ##################################################90 json_request = '/checkmempool/'+txid+'-'+str(n)+'/'+vintx+'-0'91 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')92 json_obj = json.loads(json_string)93 assert_equal(len(json_obj['utxos']), 1)94 assert_equal(json_obj['bitmap'], "10")95 #test binary response96 bb_hash = self.nodes[0].getbestblockhash()97 binaryRequest = b'\x01\x02'98 binaryRequest += hex_str_to_bytes(txid)99 binaryRequest += pack("i", n)100 binaryRequest += hex_str_to_bytes(vintx)101 binaryRequest += pack("i", 0)102 bin_response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', binaryRequest)103 output = BytesIO()104 output.write(bin_response)105 output.seek(0)106 chainHeight = unpack("i", output.read(4))[0]107 hashFromBinResponse = hex(deser_uint256(output))[2:].zfill(64)108 assert_equal(bb_hash, hashFromBinResponse) #check if getutxo's chaintip during calculation was fine109 assert_equal(chainHeight, 102) #chain height must be 102110 ############################111 # GETUTXOS: mempool checks #112 ############################113 # do a tx and don't sync114 txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)115 json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json")116 json_obj = json.loads(json_string)117 vintx = json_obj['vin'][0]['txid'] # get the vin to later check for utxo (should be spent by then)118 # get n of 0.1 outpoint119 n = 0120 for vout in json_obj['vout']:121 if vout['value'] == 0.1:122 n = vout['n']123 json_request = '/'+txid+'-'+str(n)124 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')125 json_obj = json.loads(json_string)126 assert_equal(len(json_obj['utxos']), 0) #there should be an outpoint because it has just added to the mempool127 json_request = '/checkmempool/'+txid+'-'+str(n)128 json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')129 json_obj = json.loads(json_string)130 assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because it has just added to the mempool131 #do some invalid requests132 json_request = '{"checkmempool'133 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'json', json_request, True)134 assert_equal(response.status, 400) #must be a 400 because we send an invalid json request135 json_request = '{"checkmempool'136 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True)137 assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request138 response = http_post_call(url.hostname, url.port, '/rest/getutxos/checkmempool'+self.FORMAT_SEPARATOR+'bin', '', True)139 assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request140 #test limits141 json_request = '/checkmempool/'142 for x in range(0, 20):143 json_request += txid+'-'+str(n)+'/'144 json_request = json_request.rstrip("/")145 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)146 assert_equal(response.status, 400) #must be a 400 because we exceeding the limits147 json_request = '/checkmempool/'148 for x in range(0, 15):149 json_request += txid+'-'+str(n)+'/'150 json_request = json_request.rstrip("/")151 response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)152 assert_equal(response.status, 200) #must be a 200 because we are within the limits153 self.nodes[0].generate(1) #generate block to not affect upcoming tests154 self.sync_all()155 ################156 # /rest/block/ #157 ################158 # check binary format159 response = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True)160 assert_equal(response.status, 200)161 assert_greater_than(int(response.getheader('content-length')), 80)162 response_str = response.read()163 # compare with block header164 response_header = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True)165 assert_equal(response_header.status, 200)166 assert_equal(int(response_header.getheader('content-length')), 80)167 response_header_str = response_header.read()168 assert_equal(response_str[0:80], response_header_str)169 # check block hex format170 response_hex = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True)171 assert_equal(response_hex.status, 200)172 assert_greater_than(int(response_hex.getheader('content-length')), 160)173 response_hex_str = response_hex.read()174 assert_equal(encode(response_str, "hex_codec")[0:160], response_hex_str[0:160])175 # compare with hex block header176 response_header_hex = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True)177 assert_equal(response_header_hex.status, 200)178 assert_greater_than(int(response_header_hex.getheader('content-length')), 160)179 response_header_hex_str = response_header_hex.read()180 assert_equal(response_hex_str[0:160], response_header_hex_str[0:160])181 assert_equal(encode(response_header_str, "hex_codec")[0:160], response_header_hex_str[0:160])182 # check json format183 block_json_string = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+'json')184 block_json_obj = json.loads(block_json_string)185 assert_equal(block_json_obj['hash'], bb_hash)186 # compare with json block header187 response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)188 assert_equal(response_header_json.status, 200)189 response_header_json_str = response_header_json.read().decode('utf-8')190 json_obj = json.loads(response_header_json_str, parse_float=Decimal)191 assert_equal(len(json_obj), 1) #ensure that there is one header in the json response192 assert_equal(json_obj[0]['hash'], bb_hash) #request/response hash should be the same193 #compare with normal RPC block response194 rpc_block_json = self.nodes[0].getblock(bb_hash)195 assert_equal(json_obj[0]['hash'], rpc_block_json['hash'])196 assert_equal(json_obj[0]['confirmations'], rpc_block_json['confirmations'])197 assert_equal(json_obj[0]['height'], rpc_block_json['height'])198 assert_equal(json_obj[0]['version'], rpc_block_json['version'])199 assert_equal(json_obj[0]['merkleroot'], rpc_block_json['merkleroot'])200 assert_equal(json_obj[0]['time'], rpc_block_json['time'])201 assert_equal(json_obj[0]['nonce'], rpc_block_json['nonce'])202 assert_equal(json_obj[0]['bits'], rpc_block_json['bits'])203 assert_equal(json_obj[0]['difficulty'], rpc_block_json['difficulty'])204 assert_equal(json_obj[0]['chainwork'], rpc_block_json['chainwork'])205 assert_equal(json_obj[0]['previousblockhash'], rpc_block_json['previousblockhash'])206 #see if we can get 5 headers in one response207 self.nodes[1].generate(5)208 self.sync_all()209 response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/5/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)210 assert_equal(response_header_json.status, 200)211 response_header_json_str = response_header_json.read().decode('utf-8')212 json_obj = json.loads(response_header_json_str)213 assert_equal(len(json_obj), 5) #now we should have 5 header objects214 # do tx test215 tx_hash = block_json_obj['tx'][0]['txid']216 json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"json")217 json_obj = json.loads(json_string)218 assert_equal(json_obj['txid'], tx_hash)219 # check hex format response220 hex_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"hex", True)221 assert_equal(hex_string.status, 200)222 assert_greater_than(int(response.getheader('content-length')), 10)223 # check block tx details224 # let's make 3 tx and mine them on node 1225 txs = []226 txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))227 txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))228 txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))229 self.sync_all()230 # check that there are exactly 3 transactions in the TX memory pool before generating the block231 json_string = http_get_call(url.hostname, url.port, '/rest/mempool/info'+self.FORMAT_SEPARATOR+'json')232 json_obj = json.loads(json_string)233 assert_equal(json_obj['size'], 3)234 # the size of the memory pool should be greater than 3x ~100 bytes235 assert_greater_than(json_obj['bytes'], 300)236 # check that there are our submitted transactions in the TX memory pool237 json_string = http_get_call(url.hostname, url.port, '/rest/mempool/contents'+self.FORMAT_SEPARATOR+'json')238 json_obj = json.loads(json_string)239 for tx in txs:240 assert_equal(tx in json_obj, True)241 # now mine the transactions242 newblockhash = self.nodes[1].generate(1)243 self.sync_all()244 #check if the 3 tx show up in the new block245 json_string = http_get_call(url.hostname, url.port, '/rest/block/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')246 json_obj = json.loads(json_string)247 for tx in json_obj['tx']:248 if not 'coinbase' in tx['vin'][0]: #exclude coinbase249 assert_equal(tx['txid'] in txs, True)250 #check the same but without tx details251 json_string = http_get_call(url.hostname, url.port, '/rest/block/notxdetails/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')252 json_obj = json.loads(json_string)253 for tx in txs:254 assert_equal(tx in json_obj['tx'], True)255 #test rest bestblock256 bb_hash = self.nodes[0].getbestblockhash()257 json_string = http_get_call(url.hostname, url.port, '/rest/chaininfo.json')258 json_obj = json.loads(json_string)259 assert_equal(json_obj['bestblockhash'], bb_hash)260if __name__ == '__main__':...

Full Screen

Full Screen

test_unicode.py

Source:test_unicode.py Github

copy

Full Screen

1import sys2import codecs3from unittest import TestCase4import simplejson as json5from simplejson.compat import unichr, text_type, b, u, BytesIO6class TestUnicode(TestCase):7 def test_encoding1(self):8 encoder = json.JSONEncoder(encoding='utf-8')9 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'10 s = u.encode('utf-8')11 ju = encoder.encode(u)12 js = encoder.encode(s)13 self.assertEqual(ju, js)14 def test_encoding2(self):15 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'16 s = u.encode('utf-8')17 ju = json.dumps(u, encoding='utf-8')18 js = json.dumps(s, encoding='utf-8')19 self.assertEqual(ju, js)20 def test_encoding3(self):21 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'22 j = json.dumps(u)23 self.assertEqual(j, '"\\u03b1\\u03a9"')24 def test_encoding4(self):25 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'26 j = json.dumps([u])27 self.assertEqual(j, '["\\u03b1\\u03a9"]')28 def test_encoding5(self):29 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'30 j = json.dumps(u, ensure_ascii=False)31 self.assertEqual(j, u'"' + u + u'"')32 def test_encoding6(self):33 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'34 j = json.dumps([u], ensure_ascii=False)35 self.assertEqual(j, u'["' + u + u'"]')36 def test_big_unicode_encode(self):37 u = u'\U0001d120'38 self.assertEqual(json.dumps(u), '"\\ud834\\udd20"')39 self.assertEqual(json.dumps(u, ensure_ascii=False), u'"\U0001d120"')40 def test_big_unicode_decode(self):41 u = u'z\U0001d120x'42 self.assertEqual(json.loads('"' + u + '"'), u)43 self.assertEqual(json.loads('"z\\ud834\\udd20x"'), u)44 def test_unicode_decode(self):45 for i in range(0, 0xd7ff):46 u = unichr(i)47 #s = '"\\u{0:04x}"'.format(i)48 s = '"\\u%04x"' % (i,)49 self.assertEqual(json.loads(s), u)50 def test_object_pairs_hook_with_unicode(self):51 s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'52 p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4),53 (u"qrt", 5), (u"pad", 6), (u"hoy", 7)]54 self.assertEqual(json.loads(s), eval(s))55 self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)56 od = json.loads(s, object_pairs_hook=json.OrderedDict)57 self.assertEqual(od, json.OrderedDict(p))58 self.assertEqual(type(od), json.OrderedDict)59 # the object_pairs_hook takes priority over the object_hook60 self.assertEqual(json.loads(s,61 object_pairs_hook=json.OrderedDict,62 object_hook=lambda x: None),63 json.OrderedDict(p))64 def test_default_encoding(self):65 self.assertEqual(json.loads(u'{"a": "\xe9"}'.encode('utf-8')),66 {'a': u'\xe9'})67 def test_unicode_preservation(self):68 self.assertEqual(type(json.loads(u'""')), text_type)69 self.assertEqual(type(json.loads(u'"a"')), text_type)70 self.assertEqual(type(json.loads(u'["a"]')[0]), text_type)71 def test_ensure_ascii_false_returns_unicode(self):72 # http://code.google.com/p/simplejson/issues/detail?id=4873 self.assertEqual(type(json.dumps([], ensure_ascii=False)), text_type)74 self.assertEqual(type(json.dumps(0, ensure_ascii=False)), text_type)75 self.assertEqual(type(json.dumps({}, ensure_ascii=False)), text_type)76 self.assertEqual(type(json.dumps("", ensure_ascii=False)), text_type)77 def test_ensure_ascii_false_bytestring_encoding(self):78 # http://code.google.com/p/simplejson/issues/detail?id=4879 doc1 = {u'quux': b('Arr\xc3\xaat sur images')}80 doc2 = {u'quux': u('Arr\xeat sur images')}81 doc_ascii = '{"quux": "Arr\\u00eat sur images"}'82 doc_unicode = u'{"quux": "Arr\xeat sur images"}'83 self.assertEqual(json.dumps(doc1), doc_ascii)84 self.assertEqual(json.dumps(doc2), doc_ascii)85 self.assertEqual(json.dumps(doc1, ensure_ascii=False), doc_unicode)86 self.assertEqual(json.dumps(doc2, ensure_ascii=False), doc_unicode)87 def test_ensure_ascii_linebreak_encoding(self):88 # http://timelessrepo.com/json-isnt-a-javascript-subset89 s1 = u'\u2029\u2028'90 s2 = s1.encode('utf8')91 expect = '"\\u2029\\u2028"'92 self.assertEqual(json.dumps(s1), expect)93 self.assertEqual(json.dumps(s2), expect)94 self.assertEqual(json.dumps(s1, ensure_ascii=False), expect)95 self.assertEqual(json.dumps(s2, ensure_ascii=False), expect)96 def test_invalid_escape_sequences(self):97 # incomplete escape sequence98 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u')99 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1')100 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12')101 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123')102 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1234')103 # invalid escape sequence104 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123x"')105 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12x4"')106 self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1x34"')107 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ux234"')108 if sys.maxunicode > 65535:109 # invalid escape sequence for low surrogate110 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u"')111 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0"')112 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00"')113 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000"')114 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000x"')115 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00x0"')116 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0x00"')117 self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\ux000"')118 def test_ensure_ascii_still_works(self):119 # in the ascii range, ensure that everything is the same120 for c in map(unichr, range(0, 127)):121 self.assertEqual(122 json.dumps(c, ensure_ascii=False),123 json.dumps(c))124 snowman = u'\N{SNOWMAN}'125 self.assertEqual(126 json.dumps(c, ensure_ascii=False),127 '"' + c + '"')128 def test_strip_bom(self):129 content = u"\u3053\u3093\u306b\u3061\u308f"130 json_doc = codecs.BOM_UTF8 + b(json.dumps(content))131 self.assertEqual(json.load(BytesIO(json_doc)), content)132 for doc in json_doc, json_doc.decode('utf8'):...

Full Screen

Full Screen

gen_build_yaml.py

Source:gen_build_yaml.py Github

copy

Full Screen

1#!/usr/bin/env python2.72# Copyright 2015 gRPC authors.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15from __future__ import print_function16import json17import pipes18import shutil19import sys20import os21import yaml22run_tests_root = os.path.abspath(os.path.join(23 os.path.dirname(sys.argv[0]),24 '../../../tools/run_tests'))25sys.path.append(run_tests_root)26import performance.scenario_config as scenario_config27configs_from_yaml = yaml.load(open(os.path.join(os.path.dirname(sys.argv[0]), '../../../build.yaml')))['configs'].keys()28def mutate_scenario(scenario_json, is_tsan):29 # tweak parameters to get fast test times30 scenario_json = dict(scenario_json)31 scenario_json['warmup_seconds'] = 032 scenario_json['benchmark_seconds'] = 133 outstanding_rpcs_divisor = 134 if is_tsan and (35 scenario_json['client_config']['client_type'] == 'SYNC_CLIENT' or36 scenario_json['server_config']['server_type'] == 'SYNC_SERVER'):37 outstanding_rpcs_divisor = 1038 scenario_json['client_config']['outstanding_rpcs_per_channel'] = max(1,39 int(scenario_json['client_config']['outstanding_rpcs_per_channel'] / outstanding_rpcs_divisor))40 return scenario_json41def _scenario_json_string(scenario_json, is_tsan):42 scenarios_json = {'scenarios': [scenario_config.remove_nonproto_fields(mutate_scenario(scenario_json, is_tsan))]}43 return json.dumps(scenarios_json)44def threads_required(scenario_json, where, is_tsan):45 scenario_json = mutate_scenario(scenario_json, is_tsan)46 if scenario_json['%s_config' % where]['%s_type' % where] == 'ASYNC_%s' % where.upper():47 return scenario_json['%s_config' % where].get('async_%s_threads' % where, 0)48 return scenario_json['client_config']['outstanding_rpcs_per_channel'] * scenario_json['client_config']['client_channels']49def guess_cpu(scenario_json, is_tsan):50 client = threads_required(scenario_json, 'client', is_tsan)51 server = threads_required(scenario_json, 'server', is_tsan)52 # make an arbitrary guess if set to auto-detect53 # about the size of the jenkins instances we have for unit tests54 if client == 0 or server == 0: return 'capacity'55 return (scenario_json['num_clients'] * client +56 scenario_json['num_servers'] * server)57def maybe_exclude_gcov(scenario_json):58 if scenario_json['client_config']['client_channels'] > 100:59 return ['gcov']60 return []61def generate_yaml():62 return {63 'tests': [64 {65 'name': 'json_run_localhost',66 'shortname': 'json_run_localhost:%s' % scenario_json['name'],67 'args': ['--scenarios_json', _scenario_json_string(scenario_json, False)],68 'ci_platforms': ['linux'],69 'platforms': ['linux'],70 'flaky': False,71 'language': 'c++',72 'boringssl': True,73 'defaults': 'boringssl',74 'cpu_cost': guess_cpu(scenario_json, False),75 'exclude_configs': ['tsan', 'asan'] + maybe_exclude_gcov(scenario_json),76 'timeout_seconds': 2*60,77 'excluded_poll_engines': scenario_json.get('EXCLUDED_POLL_ENGINES', []),78 'auto_timeout_scaling': False79 }80 for scenario_json in scenario_config.CXXLanguage().scenarios()81 if 'scalable' in scenario_json.get('CATEGORIES', [])82 ] + [83 {84 'name': 'qps_json_driver',85 'shortname': 'qps_json_driver:inproc_%s' % scenario_json['name'],86 'args': ['--run_inproc', '--scenarios_json', _scenario_json_string(scenario_json, False)],87 'ci_platforms': ['linux'],88 'platforms': ['linux'],89 'flaky': False,90 'language': 'c++',91 'boringssl': True,92 'defaults': 'boringssl',93 'cpu_cost': guess_cpu(scenario_json, False),94 'exclude_configs': ['tsan', 'asan'],95 'timeout_seconds': 6*60,96 'excluded_poll_engines': scenario_json.get('EXCLUDED_POLL_ENGINES', [])97 }98 for scenario_json in scenario_config.CXXLanguage().scenarios()99 if 'inproc' in scenario_json.get('CATEGORIES', [])100 ] + [101 {102 'name': 'json_run_localhost',103 'shortname': 'json_run_localhost:%s_low_thread_count' % scenario_json['name'],104 'args': ['--scenarios_json', _scenario_json_string(scenario_json, True)],105 'ci_platforms': ['linux'],106 'platforms': ['linux'],107 'flaky': False,108 'language': 'c++',109 'boringssl': True,110 'defaults': 'boringssl',111 'cpu_cost': guess_cpu(scenario_json, True),112 'exclude_configs': sorted(c for c in configs_from_yaml if c not in ('tsan', 'asan')),113 'timeout_seconds': 10*60,114 'excluded_poll_engines': scenario_json.get('EXCLUDED_POLL_ENGINES', []),115 'auto_timeout_scaling': False116 }117 for scenario_json in scenario_config.CXXLanguage().scenarios()118 if 'scalable' in scenario_json.get('CATEGORIES', [])119 ]120 }...

Full Screen

Full Screen

test_fail.py

Source:test_fail.py Github

copy

Full Screen

1from json.tests import PyTest, CTest2# 2007-10-053JSONDOCS = [4 # http://json.org/JSON_checker/test/fail1.json5 '"A JSON payload should be an object or array, not a string."',6 # http://json.org/JSON_checker/test/fail2.json7 '["Unclosed array"',8 # http://json.org/JSON_checker/test/fail3.json9 '{unquoted_key: "keys must be quoted"}',10 # http://json.org/JSON_checker/test/fail4.json11 '["extra comma",]',12 # http://json.org/JSON_checker/test/fail5.json13 '["double extra comma",,]',14 # http://json.org/JSON_checker/test/fail6.json15 '[ , "<-- missing value"]',16 # http://json.org/JSON_checker/test/fail7.json17 '["Comma after the close"],',18 # http://json.org/JSON_checker/test/fail8.json19 '["Extra close"]]',20 # http://json.org/JSON_checker/test/fail9.json21 '{"Extra comma": true,}',22 # http://json.org/JSON_checker/test/fail10.json23 '{"Extra value after close": true} "misplaced quoted value"',24 # http://json.org/JSON_checker/test/fail11.json25 '{"Illegal expression": 1 + 2}',26 # http://json.org/JSON_checker/test/fail12.json27 '{"Illegal invocation": alert()}',28 # http://json.org/JSON_checker/test/fail13.json29 '{"Numbers cannot have leading zeroes": 013}',30 # http://json.org/JSON_checker/test/fail14.json31 '{"Numbers cannot be hex": 0x14}',32 # http://json.org/JSON_checker/test/fail15.json33 '["Illegal backslash escape: \\x15"]',34 # http://json.org/JSON_checker/test/fail16.json35 '[\\naked]',36 # http://json.org/JSON_checker/test/fail17.json37 '["Illegal backslash escape: \\017"]',38 # http://json.org/JSON_checker/test/fail18.json39 '[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]',40 # http://json.org/JSON_checker/test/fail19.json41 '{"Missing colon" null}',42 # http://json.org/JSON_checker/test/fail20.json43 '{"Double colon":: null}',44 # http://json.org/JSON_checker/test/fail21.json45 '{"Comma instead of colon", null}',46 # http://json.org/JSON_checker/test/fail22.json47 '["Colon instead of comma": false]',48 # http://json.org/JSON_checker/test/fail23.json49 '["Bad value", truth]',50 # http://json.org/JSON_checker/test/fail24.json51 "['single quote']",52 # http://json.org/JSON_checker/test/fail25.json53 '["\ttab\tcharacter\tin\tstring\t"]',54 # http://json.org/JSON_checker/test/fail26.json55 '["tab\\ character\\ in\\ string\\ "]',56 # http://json.org/JSON_checker/test/fail27.json57 '["line\nbreak"]',58 # http://json.org/JSON_checker/test/fail28.json59 '["line\\\nbreak"]',60 # http://json.org/JSON_checker/test/fail29.json61 '[0e]',62 # http://json.org/JSON_checker/test/fail30.json63 '[0e+]',64 # http://json.org/JSON_checker/test/fail31.json65 '[0e+-1]',66 # http://json.org/JSON_checker/test/fail32.json67 '{"Comma instead if closing brace": true,',68 # http://json.org/JSON_checker/test/fail33.json69 '["mismatch"}',70 # http://code.google.com/p/simplejson/issues/detail?id=371 u'["A\u001FZ control characters in string"]',72]73SKIPS = {74 1: "why not have a string payload?",75 18: "spec doesn't specify any nesting limitations",76}77class TestFail(object):78 def test_failures(self):79 for idx, doc in enumerate(JSONDOCS):80 idx = idx + 181 if idx in SKIPS:82 self.loads(doc)83 continue84 try:85 self.loads(doc)86 except ValueError:87 pass88 else:89 self.fail("Expected failure for fail{0}.json: {1!r}".format(idx, doc))90 def test_non_string_keys_dict(self):91 data = {'a' : 1, (1, 2) : 2}92 #This is for c encoder93 self.assertRaises(TypeError, self.dumps, data)94 #This is for python encoder95 self.assertRaises(TypeError, self.dumps, data, indent=True)96class TestPyFail(TestFail, PyTest): pass...

Full Screen

Full Screen

api.gyp

Source:api.gyp Github

copy

Full Screen

1# Copyright (c) 2012 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4{5 'targets': [6 {7 'target_name': 'api',8 'type': 'static_library',9 'sources': [10 '<@(schema_files)',11 ],12 # TODO(jschuh): http://crbug.com/167187 size_t -> int13 'msvs_disabled_warnings': [ 4267 ],14 'includes': [15 '../../../../build/json_schema_bundle_compile.gypi',16 '../../../../build/json_schema_compile.gypi',17 ],18 'variables': {19 'chromium_code': 1,20 'schema_files': [21 'alarms.idl',22 'app_current_window_internal.idl',23 'app_runtime.idl',24 'app_window.idl',25 'autotest_private.idl',26 'bluetooth.idl',27 'bookmark_manager_private.json',28 'bookmarks.json',29 'chromeos_info_private.json',30 'cloud_print_private.json',31 'content_settings.json',32 'context_menus.json',33 'cookies.json',34 'debugger.json',35 'developer_private.idl',36 'dial.idl',37 'downloads.idl',38 'echo_private.json',39 'downloads_internal.idl',40 'events.json',41 'experimental_accessibility.json',42 'experimental_discovery.idl',43 'experimental_dns.idl',44 'experimental_history.json',45 'experimental_identity.idl',46 'experimental_idltest.idl',47 'experimental_infobars.json',48 'experimental_media_galleries.idl',49 'experimental_record.json',50 'experimental_system_info_cpu.idl',51 'experimental_system_info_memory.idl',52 'experimental_system_info_storage.idl',53 'extension.json',54 'file_browser_handler_internal.json',55 'file_system.idl',56 'font_settings.json',57 'history.json',58 'i18n.json',59 'idle.json',60 'managed_mode_private.json',61 'management.json',62 'media_galleries.idl',63 'media_galleries_private.idl',64 'media_player_private.json',65 'metrics_private.json',66 'networking_private.json',67 'notifications.idl',68 'omnibox.json',69 'page_capture.json',70 'page_launcher.idl',71 'permissions.json',72 'power.idl',73 'push_messaging.idl',74 'rtc_private.idl',75 'serial.idl',76 'session_restore.json',77 'socket.idl',78 'storage.json',79 'sync_file_system.idl',80 'system_indicator.idl',81 'system_info_display.idl',82 'system_private.json',83 'tab_capture.idl',84 'tabs.json',85 'terminal_private.json',86 'test.json',87 'top_sites.json',88 'usb.idl',89 'wallpaper_private.json',90 'web_navigation.json',91 'web_request.json',92 'web_socket_proxy_private.json',93 'webview.json',94 'windows.json',95 ],96 'cc_dir': 'chrome/common/extensions/api',97 'root_namespace': 'extensions::api',98 },99 'dependencies': [100 '<(DEPTH)/skia/skia.gyp:skia',101 '<(DEPTH)/sync/sync.gyp:sync',102 ],103 'conditions': [104 ['OS=="android"', {105 'schema_files!': [106 'usb.idl',107 ],108 }],109 ['OS!="chromeos"', {110 'schema_files!': [111 'file_browser_handler_internal.json',112 'rtc_private.idl',113 ],114 }],115 ],116 },117 ],...

Full Screen

Full Screen

test_for_json.py

Source:test_for_json.py Github

copy

Full Screen

1import unittest2import simplejson as json3class ForJson(object):4 def for_json(self):5 return {'for_json': 1}6class NestedForJson(object):7 def for_json(self):8 return {'nested': ForJson()}9class ForJsonList(object):10 def for_json(self):11 return ['list']12class DictForJson(dict):13 def for_json(self):14 return {'alpha': 1}15class ListForJson(list):16 def for_json(self):17 return ['list']18class TestForJson(unittest.TestCase):19 def assertRoundTrip(self, obj, other, for_json=True):20 if for_json is None:21 # None will use the default22 s = json.dumps(obj)23 else:24 s = json.dumps(obj, for_json=for_json)25 self.assertEqual(26 json.loads(s),27 other)28 def test_for_json_encodes_stand_alone_object(self):29 self.assertRoundTrip(30 ForJson(),31 ForJson().for_json())32 def test_for_json_encodes_object_nested_in_dict(self):33 self.assertRoundTrip(34 {'hooray': ForJson()},35 {'hooray': ForJson().for_json()})36 def test_for_json_encodes_object_nested_in_list_within_dict(self):37 self.assertRoundTrip(38 {'list': [0, ForJson(), 2, 3]},39 {'list': [0, ForJson().for_json(), 2, 3]})40 def test_for_json_encodes_object_nested_within_object(self):41 self.assertRoundTrip(42 NestedForJson(),43 {'nested': {'for_json': 1}})44 def test_for_json_encodes_list(self):45 self.assertRoundTrip(46 ForJsonList(),47 ForJsonList().for_json())48 def test_for_json_encodes_list_within_object(self):49 self.assertRoundTrip(50 {'nested': ForJsonList()},51 {'nested': ForJsonList().for_json()})52 def test_for_json_encodes_dict_subclass(self):53 self.assertRoundTrip(54 DictForJson(a=1),55 DictForJson(a=1).for_json())56 def test_for_json_encodes_list_subclass(self):57 self.assertRoundTrip(58 ListForJson(['l']),59 ListForJson(['l']).for_json())60 def test_for_json_ignored_if_not_true_with_dict_subclass(self):61 for for_json in (None, False):62 self.assertRoundTrip(63 DictForJson(a=1),64 {'a': 1},65 for_json=for_json)66 def test_for_json_ignored_if_not_true_with_list_subclass(self):67 for for_json in (None, False):68 self.assertRoundTrip(69 ListForJson(['l']),70 ['l'],71 for_json=for_json)72 def test_raises_typeerror_if_for_json_not_true_with_object(self):73 self.assertRaises(TypeError, json.dumps, ForJson())...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { withKnobs } from '@storybook/addon-knobs';3import { withInfo } from '@storybook/addon-info';4import { withReadme } from 'storybook-readme';5import readme from './readme.md';6import { withDocs } from 'storybook-readme';7import { withNotes } from '@storybook/addon-notes';8import { withA11y } from '@storybook/addon-a11y';9import { withTests } from '@storybook/addon-jest';10import { withViewport } from '@storybook/addon-viewport';11import { withConsole } from '@storybook/addon-console';12import { withOptions } from '@storybook/addon-options';13import { withBackgrounds } from '@storybook/addon-backgrounds';14import { withLinks } from '@storybook/addon-links';15import { withActions } from '@storybook/addon-actions';16import { withState } from '@dump247/storybook-state';17import { withSmartKnobs } from 'storybook-addon-smart-knobs';18import { withStorySource } from '@storybook/addon-storysource';19import { withPropsTable } from 'storybook-addon-react-docgen';20import { withTests } from '@storybook/addon-jest';21import { withOptions } from '@storybook/addon-options';22import { withInfo } from '@storybook/addon-info';23import { withReadme } from 'storybook-readme';24import { withDocs } from 'storybook-readme';25import { withKnobs } from '@storybook/addon-knobs';26import { withNotes } from '@storybook/addon-notes';27import { withA11y } from '@storybook/addon-a11y';28import { withViewport } from '@storybook/addon-viewport';29import { withConsole } from '@storybook/addon-console';30import { withBackgrounds } from '@storybook/addon-backgrounds';31import { withLinks } from '@storybook/addon-links';32import { withActions } from '@storybook/addon-actions';33import { withState } from '@dump247/storybook-state';34import { withSmartKnobs } from 'storybook-addon-smart-knobs';35import { withStorySource } from '@storybook/addon-storysource';36import { withPropsTable } from 'storybook-addon-react-docgen';37import { withTests } from '@storybook/addon-jest';38import { withOptions } from '@storybook/addon-options';39import { withInfo } from '@storybook

Full Screen

Using AI Code Generation

copy

Full Screen

1const { storiesOf } = require('@storybook/react');2const { withKnobs, text } = require('@storybook/addon-knobs');3const { withReadme } = require('storybook-readme');4const readme = require('./README.md');5storiesOf('Button', module)6 .addDecorator(withKnobs)7 .add('with text', withReadme(readme, () => {8 const label = text('Label', 'Hello Button');9 return <button>{label}</button>;10 }));11import Button from 'button';12Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):13Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):14Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):15Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful