Best Python code snippet using avocado_python
test_user_tests.py
Source:test_user_tests.py  
1#!/usr/bin/python2.52#3# Copyright 2009 Google Inc.4#5# Licensed under the Apache License, Version 2.0 (the 'License')6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9#     http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an 'AS IS' BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16"""Test admin_rankers."""17__author__ = 'elsigh@google.com (Lindsey Simon)'18import datetime19import logging20import re21import unittest22from django.test.client import Client23from google.appengine.api import memcache24from google.appengine.api import users25from google.appengine.ext import db26from base import util27from categories import all_test_sets28from models import result_stats29import models.user_test30import mock_data31import settings32from third_party import mox33def repeat_to_length(string_to_expand, length):34  return (string_to_expand * ((length/len(string_to_expand))+1))[:length]35class TestModels(unittest.TestCase):36  def testUser(self):37    current_user = users.get_current_user()38    u = models.user_test.User.get_or_insert(current_user.user_id())39    u.email = current_user.email()40    u.save()41    user_q = models.user_test.User.get_by_key_name(current_user.user_id())42    self.assertTrue(user_q.email, current_user.email())43  def testGetTestSetFromResultString(self):44    current_user = users.get_current_user()45    u = models.user_test.User.get_or_insert(current_user.user_id())46    test = models.user_test.Test(user=u, name='Fake Test',47                                 url='http://fakeurl.com/test.html',48                                 description='stuff')49    test.save()50    results_str = 'test_1=0,test_2=1'51    test_set_category = 'usertest_%s' % test.key()52    test_set = models.user_test.Test.get_test_set_from_results_str(53        test_set_category, results_str)54    self.assertTrue(test_set != None)55    self.assertEqual(test_set.category, test_set_category)56    self.assertEqual(len(test_set.tests), 2)57    self.assertEqual('test_1', test_set.tests[0].key)58    self.assertEqual('test_2', test_set.tests[1].key)59  def testGetTestSetFromResultStringThrowsOnLongKeys(self):60    current_user = users.get_current_user()61    u = models.user_test.User.get_or_insert(current_user.user_id())62    test = models.user_test.Test(user=u, name='Fake Test',63                                 url='http://fakeurl.com/test.html',64                                 description='stuff')65    test.save()66    too_long_key_name = repeat_to_length('x',67                                         models.user_test.MAX_KEY_LENGTH + 1)68    results_str = 'test_1=0,test_2=1,%s=2' % too_long_key_name69    test_set_category = 'usertest_%s' % test.key()70    self.assertRaises(models.user_test.KeyTooLong,71        models.user_test.Test.get_test_set_from_results_str,72        test_set_category, results_str)73class TestBasics(unittest.TestCase):74  def setUp(self):75    self.client = Client()76  def testHowto(self):77    response = self.client.get('/user/tests/howto')78    self.assertEqual(200, response.status_code)79  def testGetSettings(self):80    response = self.client.get('/user/settings')81    self.assertEqual(200, response.status_code)82  def testCreateTestBad(self):83    csrf_token = self.client.get('/get_csrf').content84    data = {85      'name': '',86      'url': 'http://fakeurl.com/test.html',87      'description': 'whatever',88      'csrf_token': csrf_token,89    }90    response = self.client.post('/user/tests/create', data)91    self.assertEqual(200, response.status_code)92    tests = db.Query(models.user_test.Test)93    self.assertEquals(0, tests.count())94  def testCreateTestOk(self):95    csrf_token = self.client.get('/get_csrf').content96    data = {97      'name': 'FakeTest',98      'url': 'http://fakeurl.com/test.html',99      'description': 'whatever',100      'csrf_token': csrf_token,101    }102    response = self.client.post('/user/tests/create', data)103    # Should redirect to /user/settings when all goes well.104    self.assertEqual(302, response.status_code)105    tests = db.Query(models.user_test.Test)106    self.assertEquals(1, tests.count())107class TestWithData(unittest.TestCase):108  def setUp(self):109    self.client = Client()110    current_user = users.get_current_user()111    u = models.user_test.User.get_or_insert(current_user.user_id())112    u.email = current_user.email()113    u.save()114    meta = models.user_test.TestMeta().save()115    self.test = models.user_test.Test(user=u, name='Fake Test',116                                      url='http://fakeurl.com/test.html',117                                      description='stuff', sandboxid='sand',118                                      meta=meta)119    self.test.save()120  def saveData(self):121    """Other tests call this function to save simple data."""122    params = {123      'category': self.test.get_memcache_keyname(),124      'results': 'apple=1,banana=20000,coconut=400000',125    }126    csrf_token = self.client.get('/get_csrf').content127    params['csrf_token'] = csrf_token128    response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)129    self.assertEqual(204, response.status_code)130  def testDataValueGreateThanMaxFails(self):131    params = {132      'category': self.test.get_memcache_keyname(),133      'results': 'apple=%s,banana=2,coconut=4' %134          str(models.user_test.MAX_VALUE + 1),135    }136    csrf_token = self.client.get('/get_csrf').content137    params['csrf_token'] = csrf_token138    response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)139    self.assertEqual(500, response.status_code)140  def testDataWithTooManyKeysFails(self):141    results_list = []142    for i in range(models.user_test.MAX_KEY_COUNT + 1):143      results_list.append('key%s=data%s' % (i,i))144    params = {145      'category': self.test.get_memcache_keyname(),146      'results': ','.join(results_list),147    }148    csrf_token = self.client.get('/get_csrf').content149    params['csrf_token'] = csrf_token150    response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)151    self.assertEqual(500, response.status_code)152  def testUpdateTestMeta(self):153    # Invoke the deferred handler forcefully since the SDK won't run154    # our deferred tasks.155    params = {156      'category': self.test.get_memcache_keyname(),157      'results': 'apple=1,banana=2,coconut=4',158    }159    csrf_token = self.client.get('/get_csrf').content160    params['csrf_token'] = csrf_token161    response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)162    self.assertFalse(hasattr(self.test.meta, 'apple_min_value'))163    models.user_test.update_test_meta(self.test.key(),164        [['apple', '1'], ['banana', '2'], ['coconut', '3']])165    # update our reference166    meta = models.user_test.TestMeta.get(self.test.meta.key())167    self.assertTrue(hasattr(meta, 'apple_min_value'))168    self.assertTrue(hasattr(meta, 'apple_max_value'))169    self.assertTrue(hasattr(meta, 'coconut_min_value'))170    self.assertTrue(hasattr(meta, 'coconut_max_value'))171    self.assertEquals(1, meta.apple_min_value)172    self.assertEquals(1, meta.apple_max_value)173    self.assertEquals(2, meta.banana_min_value)174    self.assertEquals(2, meta.banana_max_value)175    self.assertEquals(3, meta.coconut_min_value)176    self.assertEquals(3, meta.coconut_max_value)177    models.user_test.update_test_meta(self.test.key(),178        [['apple', '0'], ['banana', '2'], ['coconut', '30']])179    # update our reference180    meta = models.user_test.TestMeta.get(self.test.meta.key())181    self.assertEquals(0, meta.apple_min_value)182    self.assertEquals(1, meta.apple_max_value)183    self.assertEquals(2, meta.banana_min_value)184    self.assertEquals(2, meta.banana_max_value)185    self.assertEquals(3, meta.coconut_min_value)186    self.assertEquals(30, meta.coconut_max_value)187  def testUserBeaconJsReturn(self):188    response = self.client.get('/user/beacon/%s' % self.test.key())189    self.assertEquals('text/javascript', response['Content-type'])190    # There should be no callback setTimeout in the page.191    self.assertFalse(re.search('window.setTimeout', response.content))192    # There should be no sandboxid in the page.193    self.assertFalse(re.search('sandboxid', response.content))194    # There test_result_var name should be the default.195    self.assertTrue(re.search(settings.USER_TEST_RESULTS_VAR_DEFAULT,196                               response.content))197    # Now test a beacon with a callback specified.198    # This is a regex test ensuring it's there in a setTimeout.199    params = {'callback': 'MyFunction', 'sandboxid': 'foobar'}200    response = self.client.get('/user/beacon/%s' % self.test.key(), params)201    self.assertEquals('text/javascript', response['Content-type'])202    self.assertTrue(re.search('window.setTimeout\(%s' % params['callback'],203        response.content))204    self.assertTrue(re.search("'sandboxid': '%s'" % params['sandboxid'],205        response.content))206    # Now test a test_results_var specified.207    params = {'test_results_var': 'MyFunkyVar'}208    response = self.client.get('/user/beacon/%s' % self.test.key(), params)209    self.assertEquals('text/javascript', response['Content-type'])210    # The default should not be present, but our custom one should.211    self.assertFalse(re.search(settings.USER_TEST_RESULTS_VAR_DEFAULT,212                               response.content))213    self.assertTrue(re.search('MyFunkyVar', response.content))214  def testBeaconResultsTableGvizData(self):215    self.saveData()216    response = self.client.get('/gviz_table_data',217        {'category': 'usertest_%s' % self.test.key(), 'v': '3'},218        **mock_data.UNIT_TEST_UA)219    self.assertEqual(200, response.status_code)220    # Note that gviz data has thousands formatted with commas.221    self.assertEqual("google.visualization.Query.setResponse({'version':'0.6', 'reqId':'0', 'status':'OK', 'table': {cols:[{id:'ua',label:'UserAgent',type:'string'},{id:'apple',label:'apple',type:'number'},{id:'banana',label:'banana',type:'number'},{id:'coconut',label:'coconut',type:'number'},{id:'numtests',label:'# Tests',type:'number'}],rows:[{c:[{v:'other',f:'Other',p:{'className':'rt-ua-cur'}},{v:100,f:'1',p:{}},{v:100,f:'20,000',p:{}},{v:100,f:'400,000',p:{}},{v:1}]}]}});",222        response.content)223  def NOtestBeaconResultsTable(self):224    self.saveData()225    response = self.client.get('/user/tests/table/%s' % self.test.key(),226        {'v': '3'},227        **mock_data.UNIT_TEST_UA)228    self.assertEqual(200, response.status_code)229    self.assertEqual('text/html', response['Content-type'])230    strings_to_test_for = [231      # test.name232      '<h3>Fake Test</h3>',233      # test.description234      '<p>stuff</p>',235      # Hidden form field in the browser v select.236      #('<input type="hidden" name="category" '237      # 'value="usertest_%s">' % self.test.key()),238      # Ensures that 1 test was saved and that full category update worked.239      #'1\s+test\s+from\s+1\s+browser',240      # test_keys are there as headers241      'apple', 'banana', 'coconut',242    ]243    for string_value in strings_to_test_for:244      self.assertTrue(re.search(string_value, response.content), string_value)245  def testBeaconResultsTableJSON(self):246    self.saveData()247    response = self.client.get('/user/tests/table/%s' % self.test.key(),248        {'v': '3', 'o': 'json'},249        **mock_data.UNIT_TEST_UA)250    self.assertEqual(200, response.status_code)251    self.assertEqual('application/json', response['Content-type'])252    self.assertTrue(re.search(253        '"category": "usertest_%s"' % self.test.key(),254        response.content))255    # callback test256    response = self.client.get('/user/tests/table/%s' % self.test.key(),257        {'v': '3', 'o': 'json', 'callback': 'myFn'},258        **mock_data.UNIT_TEST_UA)259    self.assertEqual(200, response.status_code)260    self.assertEqual('application/json', response['Content-type'])261    self.assertTrue(re.search(262        '"category": "usertest_%s"' % self.test.key(),263        response.content))264    self.assertTrue(re.search('^myFn\(\{', response.content))265  def testBeaconWithSandboxId(self):266    params = {267      'category': self.test.get_memcache_keyname(),268      'results': 'apple=1,banana=2,coconut=4',269    }270    # Run 10 times.271    for i in range(11):272      csrf_token = self.client.get('/get_csrf').content273      params['csrf_token'] = csrf_token274      response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)275      self.assertEqual(204, response.status_code)276    # The 11th should bomb due to IP throttling.277    csrf_token = self.client.get('/get_csrf').content278    params['csrf_token'] = csrf_token279    response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)280    self.assertEqual(util.BAD_BEACON_MSG + 'IP', response.content)281    # But we should be able to run 11 beacons (i.e. 10 + 1) with a sandboxid.282    params['sandboxid'] = self.test.sandboxid283    # Run 11 times284    for i in range(12):285      csrf_token = self.client.get('/get_csrf').content286      params['csrf_token'] = csrf_token287      response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)288      self.assertEqual(204, response.status_code,289          'Failed on run %s with sandboxid %s' % (i, params['sandboxid']))290class TestAliasedUserTest(unittest.TestCase):291  """Using HTML5 as an example."""292  def setUp(self):293    self.client = Client()294    current_user = users.get_current_user()295    u = models.user_test.User.get_or_insert(current_user.user_id())296    u.email = current_user.email()297    u.save()298    test = models.user_test.Test(user=u, name='Fake Test',299                                 url='http://fakeurl.com/test.html',300                                 description='stuff')301    # Because GAEUnit won't run the deferred taskqueue properly.302    test.test_keys = ['apple', 'coconut', 'banana']303    test.save()304    self.test = test305    self.test_set = mock_data.MockUserTestSet()306    self.test_set.user_test_category = test.get_memcache_keyname()307    #all_test_sets.AddTestSet(self.test_set)308    params = {309      'category': self.test.get_memcache_keyname(),310      'results': 'apple=1,banana=2,coconut=4',311    }312    csrf_token = self.client.get('/get_csrf').content313    params['csrf_token'] = csrf_token314    response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)315    self.assertEqual(204, response.status_code)316  def testResultStats(self):317    stats = {318      'Other': {319         'summary_display': '7/3',320         'total_runs': 1,321         'summary_score': 233,322         'results': {323            'apple': {'score': 100, 'raw_score': 1, 'display': 1},324            'banana': {'score': 100, 'raw_score': 2, 'display': 2},325            'coconut': {'score': 100, 'raw_score': 4, 'display': 4},326         }327      },328      'total_runs': 1,329    }330    # First get results for the UserTest test_set331    test_set = self.test.get_test_set_from_test_keys(332        ['apple', 'banana', 'coconut'])333    results = result_stats.CategoryStatsManager.GetStats(334        test_set, browsers=('Other',),335        test_keys=['apple', 'banana', 'coconut'], use_memcache=False)336    self.assertEqual(stats, results)337    # Our MockTestSet has GetTestScoreAndDisplayValue &338    # GetRowScoreAndDisplayValue339    stats = {340      'Other': {341        'summary_display': '7',342        'total_runs': 1,343        'summary_score': 14,344        'results': {345          'apple': {'score': 2, 'raw_score': 1, 'display': 'd:2'},346          'banana': {'score': 4, 'raw_score': 2, 'display': 'd:4'},347          'coconut': {'score': 8, 'raw_score': 4, 'display': 'd:8'},348        }349      },350      'total_runs': 1,351    }352    # Now see if the test_set with user_test_category gets the same.353    results = result_stats.CategoryStatsManager.GetStats(354        self.test_set, browsers=('Other',),355        test_keys=['apple', 'banana', 'coconut'], use_memcache=False)356    self.assertEqual(stats, results)357class TestAPI(unittest.TestCase):358  def setUp(self):359    self.client = Client()360  def testCreateTestFailsWithInvalidApiKey(self):361    data = {362      'name': 'Test test',363      'url': 'http://fakeurl.com/test.html',364      'description': 'whatever',365      'api_key': 'invalid key'366    }367    response = self.client.post('/user/tests/create', data)368    self.assertEqual(200, response.status_code)369    tests = db.Query(models.user_test.Test)370    self.assertEquals(0, tests.count())371    self.assertTrue(re.search('No user was found', response.content))372  def testCreateTestOk(self):373    current_user = users.get_current_user()374    user = models.user_test.User.get_or_insert(current_user.user_id())375    data = {376      'name': 'Test test',377      'url': 'http://fakeurl.com/test.html',378      'description': 'whatever',379      'api_key': user.key().name()380    }381    response = self.client.get('/user/tests/create', data)382    self.assertEqual(200, response.status_code)383    tests = db.Query(models.user_test.Test)384    self.assertEquals(1, tests.count())...test_config_category.py
Source:test_config_category.py  
1import pytest2from sources.config.config import Config3from sources.domain.category import Category4def test_set_category(mapping_category):5    config = Config(mapping_category=mapping_category)6    assert config.mapping_category == mapping_category7def test_make_category_obj(mapping_category):8    config = Config(mapping_category=mapping_category)9    config.make_category()...test_add_quiz.py
Source:test_add_quiz.py  
1import unittest2from quiz.add import add_quiz3class TestAddQuiz(unittest.TestCase):4    def test_set_category(self):5        add = add_quiz.AddQuiz(category='QA')6        question = add.set_category()7        self.assertEqual(question, 'QA')8    def test_aset_category2(self):9        add = add_quiz.AddQuiz(category='QC')10        question = add.set_category()...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
