Best Python code snippet using playwright-python
interface.py
Source:interface.py  
1#!/usr/bin/python2.52# coding=utf-83# -*- encoding: utf-8 -*-4import sys, string, codecs, xml, re, Ft;5from Ft.Xml.XPath import Evaluate;6sys.stdout = codecs.getwriter('utf-8')(sys.stdout);7sys.stderr = codecs.getwriter('utf-8')(sys.stderr);8#9#	This class implements the HTML interface for the 10#	forms. If you want to change how they look, make11#	the change here. 12#13class Interface: #{14	15	def display(self, post_data): #{16		if post_data['committing'] == 'yes': #{17			left_entrada = self.show_entrada(post_data, 'left');18			bidix_entrada = self.show_entrada(post_data, 'bidix');19			right_entrada = self.show_entrada(post_data, 'right');20			print '<pre>';21			print left_entrada.replace('<', '<').replace('>', '>');22			print "\n";23			print bidix_entrada.replace('<', '<').replace('>', '>');24			print "\n";25			print right_entrada.replace('<', '<').replace('>', '>');26			print '</pre>';27			selected_pair = post_data['selected_pair'];28			pairs = post_data['pairs'];29			post_data['left_dictionary'].append(left_entrada, post_data['left_lemma'], post_data['right_lemma']);30			post_data['bidix_dictionary'].append(bidix_entrada, post_data['left_lemma'], post_data['right_lemma']);31			post_data['right_dictionary'].append(right_entrada, post_data['left_lemma'], post_data['right_lemma']);32                	print '<a href="http://xixona.dlsi.ua.es:8080/' + post_data['selected_pair'] + '">again!</a>';33			return '';34		#}35                #print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';36                print '<html>';37                print '<head>';38                print '  <title>Apertium dictionary management</title>';39                print '  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> ';40                print '  <link rel="stylesheet" type="text/css" href="/static/styles/default.css"/>';41                print '  <script src="/static/js/boxover.js"></script> ';42                print '</head>';43                print '<body>';44                print '<form action="add" method="POST" name="dixform">';45		######################################################################################################46		# Header47		######################################################################################################48                print '<div class="header">';49                print '  <div class="leftm">';50                print '    <a href="http://xixona.dlsi.ua.es:8080/">Home</a>';51		print '  </div>';52                print '  <div class="middlem">                                                            <!-- Header -->';53                print '    Language pair: <select name="selected_pair" onChange="dixform.submit();">';54                for pair in post_data['pairs'].keys(): #{55                        if pair == post_data['selected_pair']: #{56                                print '         <option value="' + pair + '" selected>' + pair + '</option>';57                        else: #{58                                print '         <option value="' + pair + '">' + pair + '</option>';59			#}60		#}61                print '    </select>';62                print '    Part-of-speech: <select name="selected_tag" onChange="dixform.submit();">';63                for tag in post_data['tags'].keys(): #{64                        if tag == post_data['selected_tag']: #{65                                print '         <option value="' + tag + '" selected>' + tag + '</option>';66                        else: #{67                                print '         <option value="' + tag + '">' + tag + '</option>';68			#}69		#}70                print '    </select>';71                print '  </div>';72		print '  <div class="rightm">';73                print '    ca · en · es';74                print '  </div>';75		print '</div>';76		######################################################################################################77		# Left side78		######################################################################################################79		print '<div class="container800">';80                print '  <div class="row">';81                print '    <div class="leftm"> <!-- Left -->';82                print '      <div class="container">';83                print '        <div class="row">';84		print '          <div class="left">';85                print '            Lemma:<sup><span class="tooltip" title="header=[Lemma] body=[Type in the lemma, or citation form of the word you wish to add.]">?</span></sup>';86		print '          </div>';87		print '          <div class="left">';88                print '            <input type="text" name="left_lemma" value="' + post_data['left_lemma'] + '">';89		print '          </div>';90		print '        </div>';91		print '        <div class="row">';92		print '          <div class="left">';93                print '            Paradigm:<sup><span class="tooltip" title="header=[Paradigm] body=[Paradigms define how a word inflects, select the one that fits the lemma you added.]">?</span></sup>';94		print '          </div>';95		print '          <div class="left">';96                print '            <select name="left_paradigm">';97		ordered_list_paradigms_left = [];98		for paradigm in post_data['left_paradigms']: #{99			ordered_list_paradigms_left.append(paradigm[::-1]);100		#}101	102		ordered_list_paradigms_left.sort();103		for left_p in ordered_list_paradigms_left:104			left_p = left_p[::-1];105                        if post_data['left_display_mode'] == 'list' and left_p not in post_data['left_glosses']: #{106                                continue;107			#}108                        if left_p == post_data['left_paradigm']: #{109                                if left_p in post_data['left_glosses']: #{110                                        print '                <option value="' + left_p + '" selected>' + post_data['left_glosses'][left_p] + '</option>';111                                else: #{112                                        print '                <option value="' + left_p + '" selected>' + left_p + '</option>';113                        else: #{114                                if left_p in post_data['left_glosses']: #{115                                        print '                <option value="' + left_p + '">' + post_data['left_glosses'][left_p] + '</option>';116                                else: #{117                                        print '                <option value="' + left_p + '">' + left_p + '</option>';118				#}119			#}120		#}121                print '          </select>';122		print '        </div>';123		print '      </div>';124		l_alternatives = post_data['left_alternatives'];125		if l_alternatives is not type(None) and len(l_alternatives) > 0: #{126	                print '    <div class="row">';127			print '      <div class="left">';128	                print '        Alternative:<sup><span class="tooltip" title="header=[Comment] body=[Linguistic alternative.]">?</span></sup>';129			print '      </div>';130			print '      <div class="left">';131                	print '        <select name="left_alternative">';132			for left_a in l_alternatives: #{133				if left_a == post_data['left_alternative']: #{134					print '          <option value="' + left_a + '" selected>' + l_alternatives[left_a] + '</option>';135				else: #{136					print '          <option value="' + left_a + '">' + l_alternatives[left_a] + '</option>';137				#}138			#}139                	print '        </select>';140			print '      </div>';141			print '    </div>';142		#}143                print '      <div class="row">';144		print '        <div class="left">';145                print '          Comment:<sup><span class="tooltip" title="header=[Comment] body=[Optional comment or gloss.]">?</span></sup>';146		print '        </div>';147		print '        <div class="left">';148                print '          <input type="text" name="left_comment" value="' + post_data['left_comment'] + '">';149		print '        </div>';150		print '      </div>';151		print '    </div>';152		print '    <div class="inflection">';153		self.show_preview(post_data, 'left');154		print '    </div>';155		print '  </div>';156		#################################################################################################157                print '    <!-- Bidix side -->';158                print '  <div class="middlem">';159		bi_alternatives = post_data['bidix_alternatives'];160		if bi_alternatives is not type(None) and len(bi_alternatives) > 0: #{161	                print '    <div class="row">';162			print '      <div class="cell">';163                	print '        <select name="bidix_alternative">';164			for bidix_a in bi_alternatives: #{165				print '          <option value="' + bidix_a + '">' + bi_alternatives[bidix_a] + '</option>';166			#}167                	print '        </select>';168			print '      </div>';169			print '    </div>';170		#}171		print '    <div class="row">';172		print '      <div class="cell">';173                if post_data['restriction'] != 'LR' and post_data['restriction'] != 'RL': #{174                        print '    <input type="radio" name="restriction" value="none" checked/>ââ';175                else: #{176                        print '    <input type="radio" name="restriction" value="none" />ââ';177                #}178		print '      </div>';179		print '    </div>';180		print '    <div class="row">';181		print '      <div class="cell">';182                if post_data['restriction'] == 'LR': #{183                        print '    <input type="radio" name="restriction" value="LR" checked/>ââ';184                else: #{185                        print '    <input type="radio" name="restriction" value="LR" />ââ';186                #}187		print '      </div>';188		print '    </div>';189		print '    <div class="row">';190		print '      <div class="cell">';191                if post_data['restriction'] == 'RL': #{192                        print '    <input type="radio" name="restriction" value="RL" checked/>ââ';193                else: #{194                        print '    <input type="radio" name="restriction" value="RL" />ââ';195                #}196		print '      </div>';197		print '    </div>';198		print '    <div class="row">';199                print '      <input type="reset" name="clear_box" value="Reset" />';200                print '      <input type="submit" name="preview_box" value="Preview" />';201                print '      <input type="submit" name="commit_box" value="Commit" />';202		print '    </div>';203		print '  </div>';204		############################################################################################205                print '  <div class="leftm"> <!-- Right -->';206		print '    <div id="left" class="container">';207                print '      <div class="row">';208                print '        <div class="left">';209                print '          Lemma:<sup><span class="tooltip" title="header=[Lemma] body=[Type in the lemma, or citation form of the word you wish to add.]">?</span></sup>';210		print '        </div>';211                print '        <div class="left">';212                print '          <input type="text" name="right_lemma" value="' + post_data['right_lemma'] + '">';213		print '        </div>';214		print '      </div>';215		print '      <div class="row">';216                print '        <div class="left">';217                print '          Paradigm:<sup><span class="tooltip" title="header=[Paradigm] body=[Paradigms define how a word inflects, select the one that fits the lemma you added.]">?</span></sup>';218		print '        </div>';219                print '        <div class="left">';220                print '          <select name="right_paradigm">';221		ordered_list_paradigms_right = [];222		for paradigm in post_data['right_paradigms']: #{223			ordered_list_paradigms_right.append(paradigm[::-1]);224		#}225	226		ordered_list_paradigms_right.sort();227		for right_p in ordered_list_paradigms_right: #{228			right_p = right_p[::-1];229                        if post_data['right_display_mode'] == 'list' and right_p not in post_data['right_glosses']: #{230                                continue;231                        #}232                        if right_p == post_data['right_paradigm']: #{233                                if right_p in post_data['right_glosses']: #{234                                        print '                <option value="' + right_p + '" selected>' + post_data['right_glosses'][right_p] + '</option>';235                                else: #{236                                        print '                <option value="' + right_p + '" selected>' + right_p + '</option>';237                        else: #{238                                if right_p in post_data['right_glosses']: #{239                                        print '                <option value="' + right_p + '">' + post_data['right_glosses'][right_p] + '</option>';240                                else: #{241                                        print '                <option value="' + right_p + '">' + right_p + '</option>';242                                #}243                        #}244                #}245                print '        </select>';246		print '      </div>';247		print '    </div>';248		r_alternatives = post_data['right_alternatives'];249		if r_alternatives is not type(None) and len(r_alternatives) > 0: #{250	                print '    <div class="row">';251			print '      <div class="left">';252	                print '        Alternative:<sup><span class="tooltip" title="header=[Comment] body=[Linguistic alternative.]">?</span></sup>';253			print '      </div>';254			print '      <div class="left">';255                	print '        <select name="right_alternative">';256			for right_a in r_alternatives: #{257				if right_a == post_data['right_alternative']: #{258					print '          <option value="' + right_a + '" selected>' + r_alternatives[right_a] + '</option>';259				else: #{260					print '          <option value="' + right_a + '">' + r_alternatives[right_a] + '</option>';261				#}262			#}263                	print '        </select>';264			print '      </div>';265			print '    </div>';266		#}267                print '    <div class="row">';268		print '      <div class="left">';269                print '        Comment:<sup><span class="tooltip" title="header=[Comment] body=[Optional comment or gloss.]">?</span></sup>';270		print '      </div>';271		print '      <div class="left">';272                print '        <input type="text" name="right_comment" value="' + post_data['right_comment'] + '">';273		print '      </div>';274		print '    </div>';275		print '  </div>';276		print '  <div class="inflection">';277		self.show_preview(post_data, 'right');278                print '  </div>';279                print '</div>';280                print '</div>';281		###############################################################################################282		# Footer to show entradas283		###############################################################################################284		print '<div class="row">';285		print '  <div class="leftm">';286		left_entrada = self.show_entrada(post_data, 'left');287		print '    <pre>';288		print left_entrada.replace('<', '<').replace('>', '>');289		print '    </pre>';290		print '  </div>';291		print '  <div class="middlem">';292		bidix_entrada = self.show_entrada(post_data, 'bidix');293		print '<pre>';294		print bidix_entrada.replace('<', '<').replace('>', '>');295		print '</pre>';296		print '  </div>';297		print '  <div class="rightm">';298		right_entrada = self.show_entrada(post_data, 'right');299		print '  <pre>';300		print right_entrada.replace('<', '<').replace('>', '>');301		print '  </pre>';302		print '  </div>';303		print '</div>';304                print '</form>';305                print '</body>';306                print '</html>';307			308		return '';309	#}310	def show_preview(self, post_data, _side): #311		print >> sys.stderr, 'right paradigm: ' , post_data['right_paradigm'];312		p = _side + '_paradigm';313		if post_data['previewing'] == 'on': #{314			paradigm = post_data[_side + '_dictionary'].get_paradigm(post_data[p], post_data['selected_tag']);315			if type(paradigm) == type(None): #{316				return;317			#}318	                if type(paradigm.get_stems()) != type(None): #{319	                        for s in post_data[_side + '_paradigms'][paradigm.name].get_stems(): #{320					shows = post_data[_side + '_dictionary'].get_tag_by_tag(post_data['selected_tag']).get_list();321					if len(shows) > 0: #{322						for show in post_data[_side + '_dictionary'].get_tag_by_tag(post_data['selected_tag']).get_list(): #{323							if show == s[1]: #{324				                                print self.incondicional(post_data[_side + '_lemma'], paradigm.name) + s[0] + '<br />';325								print '<span class="symbol_list">' + s[1] + '</span>';326								print '<p />';327							#}328						#}329					else: #{330		                                print self.incondicional(post_data[_side + '_lemma'], post_data[_side + '_paradigm']) + s[0] + '<br />';331						print '<span class="symbol_list">' + s[1] + '</span>';332						print '<p />';333					#}334				#}335	                else: #{336	                        print '         No stems';337	                #}338		#}339	#}340	def show_entrada(self, post_data, _side): #{341		if post_data['previewing'] == 'on': #{342			if _side == 'bidix': #{343				dictionary = post_data[_side + '_dictionary'];344				_lemma1 = post_data['left_lemma'];345				_lemma2 = post_data['right_lemma'];346				if _lemma1 == '' or _lemma2 == '': #{347					return '';348				#}349				if post_data['bidix_alternative'] != None: #{350					_alt = post_data['bidix_alternative'];351				else: #{352					_alt = '';353				#}354	355				if type(dictionary) != None: #{356					_tag = post_data['selected_tag'];357					_comment = '';358					_restriction = post_data['restriction'];359					_author = 'webform';360					_paradigm1 = post_data['left_dictionary'].get_paradigm(post_data['left_paradigm'], _tag);361					_paradigm2 = post_data['right_dictionary'].get_paradigm(post_data['right_paradigm'], _tag);362		363		        		entrada = dictionary.generate_bidix_entrada(_lemma1, _lemma2, _paradigm1, _paradigm2, _tag, _restriction, _comment, _author, _alt);364	365					return entrada;366				#}367			#}368			if _side == 'right' or _side == 'left' and post_data[_side + '_paradigm']: #{369				dictionary = post_data[_side + '_dictionary'];370				paradigm = post_data[_side + '_dictionary'].get_paradigm(post_data[_side + '_paradigm'], post_data['selected_tag']);371				if type(paradigm) != type(None): #{372					_lemma = post_data[_side + '_lemma'];373					_restriction = post_data['restriction'];374					_paradigm = paradigm.name;375					_comment = post_data[_side + '_comment'];376					_author = 'webform';377					if _side == 'right': #{378						_alt = post_data['right_alternative'];379					elif _side == 'left': #{380						_alt = post_data['left_alternative'];381					#}382		383					if _restriction == 'LR' and _side == 'right': #{384						entrada = dictionary.generate_monodix_entrada(_lemma, _paradigm, 'RL', _comment, _author, _alt);385					elif _restriction == 'RL' and _side == 'right': #{386						entrada = dictionary.generate_monodix_entrada(_lemma, _paradigm, 'LR', _comment, _author, _alt);387					else: #{388						entrada = dictionary.generate_monodix_entrada(_lemma, _paradigm, _restriction, _comment, _author, _alt);389					#}390	391					return entrada;392				#}393			#}394		#}395		return '';396	#}397	def incondicional(self, _lemma, _paradigm): #{398		if _paradigm.count('/') < 1: #{399			return _lemma;400		#}401	402		paradigm = _paradigm.decode('utf-8');403		bar_pos = paradigm.find('/');404		und_pos = paradigm.find('_');405		chr_str = (und_pos - bar_pos) - 1;406		l = _lemma.decode('utf-8');407		r = l[0:(len(l) - chr_str)];408		return r.encode('utf-8');409	#}...tests.py
Source:tests.py  
1import os2import json3import unittest4import tempfile5from copy import deepcopy6from datetime import datetime7from dateutil.relativedelta import relativedelta8from fr_app import app9from fr_app.models import db, User, FeatureRequest, Client, ProductArea10from flask_fixtures import FixturesMixin11app.config.from_object('fr_app.settings.TestingConf')12class FeatureRequestTestCase(unittest.TestCase, FixturesMixin):13    fixtures = ['clients.json', 'product_areas.json', 'users.json']14    app, db = app, db15    post_data = {16        "user": 1,17        "client": 1,18        "product_area": 1,19        "title": "First Feature Request",20        "client_priority": 1,21        "description": "First Feature Request description",22        "target_date": str(datetime.utcnow().date())23    }24    def setUp(self):25        self.db_fd, app.config['DATABASE'] = tempfile.mkstemp()26        app.testing = True27        self.app = app.test_client()28        with app.app_context():29            db.create_all()30    def tearDown(self):31        db.drop_all()32        os.close(self.db_fd)33        os.unlink(app.config['DATABASE'])34    def test_product_area_data(self):35        """Test initial data for ProductArea model."""36        product_areas = ProductArea.query.all()37        assert len(product_areas) == ProductArea.query.count() == 438    def test_client_data(self):39        """Test initial data for Client model."""40        clients = Client.query.all()41        assert len(clients) == Client.query.count() == 342    def test_user_data(self):43        """Test initial data for User model."""44        users = User.query.all()45        assert len(users) == User.query.count() == 346    def test_feature_request_data(self):47        """Test initial data for FeatureRequest model."""48        feature_requests = FeatureRequest.query.all()49        assert len(feature_requests) == FeatureRequest.query.count() == 050    def test_creating_feature_request_no_data(self):51        response = self.app.post('/api/feature_requests/add/', data=dict())52        response_data = json.loads(response.get_data().decode('utf-8'))53        assert response_data['message'] == 'No input data provided'54    def test_creating_feature_request_valid_data(self):55        response = self.app.post(56            '/api/feature_requests/add/',57            data=json.dumps(self.post_data),58            content_type='application/json'59        )60        response_data = json.loads(response.get_data().decode('utf-8'))61        assert response_data['message'] == 'Created new feature request.'62    def test_creating_feature_request_invalid_title(self):63        post_data = deepcopy(self.post_data)64        post_data['title'] = 'less'65        response = self.app.post(66            '/api/feature_requests/add/',67            data=json.dumps(post_data),68            content_type='application/json'69        )70        response_data = json.loads(response.get_data().decode('utf-8'))71        assert response_data['errors']['title'][0] == \72            'Length must be between 6 and 255.'73    def test_creating_feature_request_past_target_date(self):74        post_data = deepcopy(self.post_data)75        now = datetime.utcnow().date()76        post_data['target_date'] = str(now - relativedelta(months=1))77        response = self.app.post(78            '/api/feature_requests/add/',79            data=json.dumps(post_data),80            content_type='application/json'81        )82        response_data = json.loads(response.get_data().decode('utf-8'))83        assert response_data['errors']['target_date'][0] == \84            'Target date must be in the future'85    def test_creating_feature_request_negative_client_priority(self):86        post_data = deepcopy(self.post_data)87        post_data['client_priority'] = -188        response = self.app.post(89            '/api/feature_requests/add/',90            data=json.dumps(post_data),91            content_type='application/json'92        )93        response_data = json.loads(response.get_data().decode('utf-8'))94        assert response_data['errors']['client_priority'][0] == \95            'Must be at least 1.'96    def test_creating_feature_request_no_user_data(self):97        post_data = deepcopy(self.post_data)98        del post_data['user']99        response = self.app.post(100            '/api/feature_requests/add/',101            data=json.dumps(post_data),102            content_type='application/json'103        )104        response_data = json.loads(response.get_data().decode('utf-8'))105        assert response_data['errors']['user'][0] == \106            'Missing data for required field.'107    def test_creating_feature_request_no_client_data(self):108        post_data = deepcopy(self.post_data)109        del post_data['client']110        response = self.app.post(111            '/api/feature_requests/add/',112            data=json.dumps(post_data),113            content_type='application/json'114        )115        response_data = json.loads(response.get_data().decode('utf-8'))116        assert response_data['errors']['client'][0] == \117            'Missing data for required field.'118    def test_creating_feature_request_no_product_area_data(self):119        post_data = deepcopy(self.post_data)120        del post_data['product_area']121        response = self.app.post(122            '/api/feature_requests/add/',123            data=json.dumps(post_data),124            content_type='application/json'125        )126        response_data = json.loads(response.get_data().decode('utf-8'))127        assert response_data['errors']['product_area'][0] == \128            'Missing data for required field.'129    def test_creating_feature_request_no_title_data(self):130        post_data = deepcopy(self.post_data)131        del post_data['title']132        response = self.app.post(133            '/api/feature_requests/add/',134            data=json.dumps(post_data),135            content_type='application/json'136        )137        response_data = json.loads(response.get_data().decode('utf-8'))138        assert response_data['errors']['title'][0] == \139            'Missing data for required field.'140    def test_creating_feature_request_check_client_priority_reordering(self):141        response = self.app.post(142            '/api/feature_requests/add/',143            data=json.dumps(self.post_data),144            content_type='application/json'145        )146        response_data = json.loads(response.get_data().decode('utf-8'))147        assert response_data['message'] == 'Created new feature request.'148        first_id, first_client_priority = \149            response_data['data'][0]['id'],\150            response_data['data'][0]['client_priority']151        assert first_id == 1152        assert first_client_priority == 1153        # sending same client_priority again will result in moving the first154        # priority to 2155        response = self.app.post(156            '/api/feature_requests/add/',157            data=json.dumps(self.post_data),158            content_type='application/json'159        )160        response_data = json.loads(response.get_data().decode('utf-8'))161        assert response_data['message'] == 'Created new feature request.'162        second_id, second_client_priority = \163            response_data['data'][0]['id'],\164            response_data['data'][0]['client_priority']165        first_fr = FeatureRequest.query.get(first_id)166        assert first_fr.id == 1167        # got reordered after adding another feature request168        assert first_fr.client_priority == 2169        assert second_id == 2170        assert second_client_priority == 1171    def test_creating_feature_request_check_client_priority_no_reordering(172            self):173        response = self.app.post(174            '/api/feature_requests/add/',175            data=json.dumps(self.post_data),176            content_type='application/json'177        )178        response_data = json.loads(response.get_data().decode('utf-8'))179        assert response_data['message'] == 'Created new feature request.'180        first_id, first_client_priority = \181            response_data['data'][0]['id'],\182            response_data['data'][0]['client_priority']183        assert first_id == 1184        assert first_client_priority == 1185        post_data = deepcopy(self.post_data)186        post_data['client_priority'] = 2187        response = self.app.post(188            '/api/feature_requests/add/',189            data=json.dumps(post_data),190            content_type='application/json'191        )192        response_data = json.loads(response.get_data().decode('utf-8'))193        assert response_data['message'] == 'Created new feature request.'194        second_id, second_client_priority = \195            response_data['data'][0]['id'],\196            response_data['data'][0]['client_priority']197        first_fr = FeatureRequest.query.get(first_id)198        assert first_fr.id == 1199        # got reordered after adding another feature request200        assert first_fr.client_priority == 1201        assert second_id == 2202        assert second_client_priority == 2203    def test_updating_feature_request_description(self):204        response = self.app.post(205            '/api/feature_requests/add/',206            data=json.dumps(self.post_data),207            content_type='application/json'208        )209        response_data = json.loads(response.get_data().decode('utf-8'))210        assert response_data['message'] == 'Created new feature request.'211        description = response_data['data'][0]['description']212        assert description == self.post_data['description']213        # update FR now214        self.post_data['description'] = "I updated description"215        response = self.app.post(216            '/api/feature_requests/1/',217            data=json.dumps(self.post_data),218            content_type='application/json'219        )220        response_data = json.loads(response.get_data().decode('utf-8'))221        assert response_data['data'][0]['description'] ==\222            self.post_data['description']223    def test_updating_feature_request_client_priority(self):224        """Create a feature with priority 1, and update it to 2"""225        response = self.app.post(226            '/api/feature_requests/add/',227            data=json.dumps(self.post_data),228            content_type='application/json'229        )230        response_data = json.loads(response.get_data().decode('utf-8'))231        assert response_data['message'] == 'Created new feature request.'232        client_priority = response_data['data'][0]['client_priority']233        assert client_priority == self.post_data['client_priority']234        # update FR now235        self.post_data['client_priority'] = 2236        response = self.app.post(237            '/api/feature_requests/1/',238            data=json.dumps(self.post_data),239            content_type='application/json'240        )241        response_data = json.loads(response.get_data().decode('utf-8'))242        assert response_data['data'][0]['client_priority'] ==\243            self.post_data['client_priority']244    def test_updating_feature_requests_client_priority(self):245        """246        Create feature requests with priority 1, and 2.247        Update the second one to be 3, check only 1 and 3 exist.248        """249        for turn in range(1, 3):250            self.post_data['client_priority'] = turn251            response = self.app.post(252                '/api/feature_requests/add/',253                data=json.dumps(self.post_data),254                content_type='application/json'255            )256            response_data = json.loads(response.get_data().decode('utf-8'))257            assert response_data['message'] == 'Created new feature request.'258            client_priority = response_data['data'][0]['client_priority']259        assert client_priority == self.post_data['client_priority']260        # update FR now261        self.post_data['client_priority'] = 3262        response = self.app.post(263            '/api/feature_requests/2/',264            data=json.dumps(self.post_data),265            content_type='application/json'266        )267        response_data = json.loads(response.get_data().decode('utf-8'))268        assert response_data['data'][0]['client_priority'] ==\269            self.post_data['client_priority']270        assert FeatureRequest.query.get(1).client_priority == 1271        assert FeatureRequest.query.get(2).client_priority == 3272    def test_creating_feature_request_invalid_target_date(self):273        post_data = deepcopy(self.post_data)274        # invalid date for November month275        post_data['target_date'] = '2018-11-31'276        response = self.app.post(277            '/api/feature_requests/add/',278            data=json.dumps(post_data),279            content_type='application/json'280        )281        response_data = json.loads(response.get_data().decode('utf-8'))282        assert response_data['errors']['target_date'][0] ==\283            'Not a valid date.'284if __name__ == '__main__':...tradeapi.py
Source:tradeapi.py  
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import time4import re5import hmac6import hashlib7import base648import httplib9import json10class BTCChina():11    def __init__(self,access=None,secret=None,tradeType=None):12        self.access_key=access13        self.secret_key=secret14        self.conn=httplib.HTTPSConnection("api.btcchina.com", 443, timeout=10)15        self.tradeType = tradeType16    def _get_tonce(self):17        return int(time.time()*1000000)18    def _get_params_hash(self,pdict):19        pstring=""20        # The order of params is critical for calculating a correct hash21        fields=['tonce','accesskey','requestmethod','id','method','params']22        for f in fields:23            if pdict[f]:24                if f == 'params':25                    # Convert list to string, then strip brackets and spaces26                    # probably a cleaner way to do this27                    param_string=re.sub("[\[\] ]","",str(pdict[f]))28                    param_string=re.sub("'",'',param_string)29                    pstring+=f+'='+param_string+'&'30                else:31                    pstring+=f+'='+str(pdict[f])+'&'32            else:33                pstring+=f+'=&'34        pstring=pstring.strip('&')35        # now with correctly ordered param string, calculate hash36        phash = hmac.new(self.secret_key, pstring, hashlib.sha1).hexdigest()37        return phash38    def _private_request(self,post_data):39        try:40            #fill in common post_data parameters41            tonce=self._get_tonce()42            post_data['tonce']=tonce43            post_data['accesskey']=self.access_key44            post_data['requestmethod']='post'45            # If ID is not passed as a key of post_data, just use tonce46            if not 'id' in post_data:47                post_data['id']=tonce48            pd_hash=self._get_params_hash(post_data)49            # must use b64 encode50            auth_string='Basic '+base64.b64encode(self.access_key+':'+pd_hash)51            headers={'Authorization':auth_string,'Json-Rpc-Tonce':tonce}52            #post_data dictionary passed as JSON53            self.conn.request("POST",'/api_trade_v1.php',json.dumps(post_data),headers)54            response = self.conn.getresponse()55            # check response code, ID, and existence of 'result' or 'error'56            # before passing a dict of results57            if response.status == 200:58                # this might fail if non-json data is returned59                resp_dict = json.loads(response.read())60                # The id's may need to be used by the calling application,61                # but for now, check and discard from the return dict62                if str(resp_dict['id']) == str(post_data['id']):63                    if 'result' in resp_dict:64                        return resp_dict['result']65                    elif 'error' in resp_dict:66                        return resp_dict['error']67            else:68                # not great error handling....69                print "status:",response.status70                print "reason:",response.reason71            return None72        except Exception, e:73            print 'Failed to get response:' + str(e)74            return None75    def get_account_info(self,post_data={}):76        post_data['method']='getAccountInfo'77        post_data['params']=[]78        return self._private_request(post_data)79    def get_market_depth(self,post_data={}):80        post_data['method']='getMarketDepth2'81        post_data['params']=[post_data['limit'],self.tradeType]82        return self._private_request(post_data)83    def buy(self,price,amount,post_data={}):84        post_data['method']='buyOrder2'85        post_data['params']=[price,amount,self.tradeType]86        return self._private_request(post_data)87    def sell(self,price,amount,post_data={}):88        post_data['method']='sellOrder'89        post_data['params']=[price,amount,self.tradeType]90        return self._private_request(post_data)91    def cancel(self,order_id,post_data={}):92        post_data['method']='cancelOrder'93        post_data['params']=[self.tradeType,order_id]94        return self._private_request(post_data)95    def request_withdrawal(self,currency,amount,post_data={}):96        post_data['method']='requestWithdrawal'97        post_data['params']=[currency,amount]98        return self._private_request(post_data)99    def get_deposits(self,currency='BTC',pending=True,post_data={}):100        post_data['method']='getDeposits'101        if pending:102            post_data['params']=[currency]103        else:104            post_data['params']=[currency,''] # empty if false105        return self._private_request(post_data)106    def get_orders(self,id=None,open_only=True,post_data={}):107        # this combines getOrder and getOrders108        if id is None:109            post_data['method']='getOrders'110            if open_only:111                post_data['params']=[]112            else:113                post_data['params']=[''] # empty if false114        else:115            post_data['method']='getOrder'116            post_data['params']=[id]117        return self._private_request(post_data)118    def get_withdrawals(self,id='BTC',pending=True,post_data={}):119        # this combines getWithdrawal and getWithdrawls120        try:121            id = int(id)122            post_data['method']='getWithdrawal'123            post_data['params']=[id]124        except:125            post_data['method']='getWithdrawals'126            if pending:127                post_data['params']=[id]128            else:129                post_data['params']=[id,''] # empty if false...btc2cnyapi.py
Source:btc2cnyapi.py  
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import time4import re5import hmac6import hashlib7import base648import httplib9import json10class BTCChina():11    def __init__(self,access=None,secret=None):12        self.access_key=access13        self.secret_key=secret14        self.conn=httplib.HTTPSConnection("api.btcchina.com", 443, timeout=10)15    def _get_tonce(self):16        return int(time.time()*1000000)17    def _get_params_hash(self,pdict):18        pstring=""19        # The order of params is critical for calculating a correct hash20        fields=['tonce','accesskey','requestmethod','id','method','params']21        for f in fields:22            if pdict[f]:23                if f == 'params':24                    # Convert list to string, then strip brackets and spaces25                    # probably a cleaner way to do this26                    param_string=re.sub("[\[\] ]","",str(pdict[f]))27                    param_string=re.sub("'",'',param_string)28                    pstring+=f+'='+param_string+'&'29                else:30                    pstring+=f+'='+str(pdict[f])+'&'31            else:32                pstring+=f+'=&'33        pstring=pstring.strip('&')34        # now with correctly ordered param string, calculate hash35        phash = hmac.new(self.secret_key, pstring, hashlib.sha1).hexdigest()36        return phash37    def _private_request(self,post_data):38        try:39            #fill in common post_data parameters40            tonce=self._get_tonce()41            post_data['tonce']=tonce42            post_data['accesskey']=self.access_key43            post_data['requestmethod']='post'44            # If ID is not passed as a key of post_data, just use tonce45            if not 'id' in post_data:46                post_data['id']=tonce47            pd_hash=self._get_params_hash(post_data)48            # must use b64 encode49            auth_string='Basic '+base64.b64encode(self.access_key+':'+pd_hash)50            headers={'Authorization':auth_string,'Json-Rpc-Tonce':tonce}51            #post_data dictionary passed as JSON52            self.conn.request("POST",'/api_trade_v1.php',json.dumps(post_data),headers)53            response = self.conn.getresponse()54            # check response code, ID, and existence of 'result' or 'error'55            # before passing a dict of results56            if response.status == 200:57                # this might fail if non-json data is returned58                resp_dict = json.loads(response.read())59                # The id's may need to be used by the calling application,60                # but for now, check and discard from the return dict61                if str(resp_dict['id']) == str(post_data['id']):62                    if 'result' in resp_dict:63                        return resp_dict['result']64                    elif 'error' in resp_dict:65                        return resp_dict['error']66            else:67                # not great error handling....68                print "status:",response.status69                print "reason:",response.reason70            return None71        except Exception, e:72            print 'Failed to get response:' + str(e)73            return None74    def get_account_info(self,post_data={}):75        post_data['method']='getAccountInfo'76        post_data['params']=[]77        return self._private_request(post_data)78    def get_market_depth(self,post_data={}):79        post_data['method']='getMarketDepth2'80        post_data['params']=[post_data['limit']]81        return self._private_request(post_data)82    def buy(self,price,amount,post_data={}):83        post_data['method']='buyOrder2'84        post_data['params']=[price,amount]85        return self._private_request(post_data)86    def sell(self,price,amount,post_data={}):87        post_data['method']='sellOrder'88        post_data['params']=[price,amount]89        return self._private_request(post_data)90    def cancel(self,order_id,post_data={}):91        post_data['method']='cancelOrder'92        post_data['params']=[order_id]93        return self._private_request(post_data)94    def request_withdrawal(self,currency,amount,post_data={}):95        post_data['method']='requestWithdrawal'96        post_data['params']=[currency,amount]97        return self._private_request(post_data)98    def get_deposits(self,currency='BTC',pending=True,post_data={}):99        post_data['method']='getDeposits'100        if pending:101            post_data['params']=[currency]102        else:103            post_data['params']=[currency,''] # empty if false104        return self._private_request(post_data)105    def get_orders(self,id=None,open_only=True,post_data={}):106        # this combines getOrder and getOrders107        if id is None:108            post_data['method']='getOrders'109            if open_only:110                post_data['params']=[]111            else:112                post_data['params']=[''] # empty if false113        else:114            post_data['method']='getOrder'115            post_data['params']=[id]116        return self._private_request(post_data)117    def get_withdrawals(self,id='BTC',pending=True,post_data={}):118        # this combines getWithdrawal and getWithdrawls119        try:120            id = int(id)121            post_data['method']='getWithdrawal'122            post_data['params']=[id]123        except:124            post_data['method']='getWithdrawals'125            if pending:126                post_data['params']=[id]127            else:128                post_data['params']=[id,''] # empty if false...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
