Пример #1
0
 def _fixture_setupP(self):
     TestRunner.setupFixture()
     if not hasattr(self, 'fixtures'):
         self.fixtures = []
     if self.fixtures[0] != 'initial_data':
         self.fixtures.insert(0, 'initial_data')
     TestCase._fixture_setup(self)
Пример #2
0
 def setUp(self):
     TestCase.setUp(self)
     self.unLieu = Lieu(libelle='Nantes - Nantes Nord')
     self.unType=TypeOffre(libelle = 'Départ')
     self.unJour=Jour('lundi')
     self.unUser=User.objects.create_user('test', '*****@*****.**', 'test1234')
     self.OffrePermanenteDep=OffrePermanente(lieu=self.unLieu,type=self.unType,jour=self.unJour,auteur=self.unUser)
 def setUp(self):
     TestCase.setUp(self)
     self.brand = Brand(self)
     self.system = System(self)
     BaseTestCase.setUp(self)
     self.create_user(username='******', email='*****@*****.**', password='******')
     self.access_token = self.brand.admin_login()
 def setUp(self):
     TestCase.setUp(self)
     self.brand = Brand(self)
     self.system = System(self)
     BaseTestCase.setUp(self)
     self.create_user(username="******", email="*****@*****.**", password="******", is_superuser=True)
     self.access_token = self.brand.admin_login()
 def setUp(self):
     TestCase.setUp(self)
     self.brand = Brand(self)
     self.system = System(self)
     BaseTestCase.setUp(self)
     self.create_user(username='******', email='*****@*****.**', password='******')
     self.create_user(username='******', email='*****@*****.**', password='******')
Пример #6
0
    def setUp(self):
        # Create RSS entry
        self.rss = models.RSS.objects.create(
            name='test_rss',
            host='http://testhost.com',
        )
        self.rss.access_token = 'aaaaa'
        self.rss.refresh_token = 'bbbbb'
        self.rss.save()

        # Mock userprofile
        self.old_usr = wstore_models.UserProfile

        self.userprofile = MagicMock()
        cred = {
            'access_token': '11111',
            'refresh_token': '22222'
        }
        self.social = MagicMock()
        self.social.extra_data = cred

        self.usr_obj = MagicMock()
        self.usr_obj.user.social_auth.filter.return_value = [self.social]
        self.userprofile.objects.get.return_value = self.usr_obj

        wstore_models.UserProfile = self.userprofile
        TestCase.setUp(self)
Пример #7
0
 def setUp(self):
     """Make the selenium connection"""
     TestCase.setUp(self)
     self.verificationErrors = []
     self.selenium = selenium("localhost", 4444, "*firefox",
                              "http://localhost:8000/")
     self.selenium.start()
Пример #8
0
def run_test(test: TestCase, result: TestResult) -> bool:
    failed = False
    test_method = get_test_method(test)

    if fast_tests_only() and is_known_slow_test(test_method):
        return failed

    test_name = full_test_name(test)

    bounce_key_prefix_for_testing(test_name)
    bounce_redis_key_prefix_for_testing(test_name)

    flush_caches_for_testing()

    if not hasattr(test, "_pre_setup"):
        msg = "Test doesn't have _pre_setup; something is wrong."
        error_pre_setup = (Exception, Exception(msg), None)  # type: Tuple[Any, Any, Any]
        result.addError(test, error_pre_setup)
        return True
    test._pre_setup()

    start_time = time.time()

    test(result)  # unittest will handle skipping, error, failure and success.

    delay = time.time() - start_time
    enforce_timely_test_completion(test_method, test_name, delay, result)
    slowness_reason = getattr(test_method, 'slowness_reason', '')
    TEST_TIMINGS.append((delay, test_name, slowness_reason))

    test._post_teardown()
    return failed
Пример #9
0
    def setUp(self):
        TestCase.setUp(self)

        self.client = SuperClient()

        settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

        from django.core.mail.backends.locmem import EmailBackend
        EmailBackend() # create the outbox

        from django.core import mail
        self.emails = mail.outbox

        from django.template import (Template, NodeList, VariableNode,
            FilterExpression)
        from django.template.debug import DebugVariableNode
        self.addTypeEqualityFunc(Template, self.assertTemplateEqual)
        # self.addTypeEqualityFunc(NodeList, self.assertListEqual)
        self.addTypeEqualityFunc(VariableNode, self.assertVariableNodeEqual)
        self.addTypeEqualityFunc(DebugVariableNode,
            self.assertVariableNodeEqual)
        self.addTypeEqualityFunc(FilterExpression,
            self.assertFilterExpressionEqual)

        import warnings
        warnings.filterwarnings('error',
            r"DateTimeField received a naive datetime",
            RuntimeWarning, r'django\.db\.models\.fields')

        from django.contrib.auth.hashers import make_password
        self.test_password = '******'
        self.test_password_encrypted = make_password(self.test_password)
Пример #10
0
    def __init__(self, *args, **kwargs):
        self.json_test_data = {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3",
            "list": [
                {
                    "subkey1": "subvalue1",
                    "subkey2": "subvalue2",
                    "subkey3": "subvalue3"
                },
                {
                    "subkey1": "subvalue1",
                    "subkey2": "subvalue2",
                    "subkey3": "subvalue3"
                },
                {
                    "subkey1": "subvalue1",
                    "subkey2": "subvalue2",
                    "subkey3": "subvalue3"
                }
            ]
        }

        TestCase.__init__(self, *args, **kwargs)
Пример #11
0
 def setUp(self):
     TestCase.setUp(self)
     u = User.objects.create_user(username='******', password='******')
     self.usuario = u
     Consumidor.objects.create(usuario=u,
                               cep='55555-001')
     self.client.login(username='******', password='******')
Пример #12
0
 def __init__(
     self,
     user,
     view_perms,
     read_perms,
     post_perms,
     new_board_perms,
     view_group=[],
     read_group=[],
     post_group=[],
     new_board_group=[],
 ):
     self.view_perms, self.read_perms, self.post_perms, self.new_board_perms, self.view_group, self.read_group, self.post_group, self.new_board_group = (
         view_perms,
         read_perms,
         post_perms,
         new_board_perms,
         view_group,
         read_group,
         post_group,
         new_board_group,
     )
     self.password = "******"
     self.test_user = user
     TestCase.__init__(self)
Пример #13
0
 def setUp(self):
     TestCase.setUp(self)
     self.event = Event(title='meeting')
     self.duration = 2
     self.eventBegin = datetime.datetime(2013, 1, 7)
     self.eventEnd = self.eventBegin + datetime.timedelta(self.duration)
     self._resetEvent()
Пример #14
0
 def setUp(self):
     # Mock the standard input
     self.tested_mod.stdin = MagicMock()
     self.tested_mod.stdin.readline.return_value = 'y '
     # Mock rmtree
     self.tested_mod.rmtree = MagicMock()
     TestCase.setUp(self)
Пример #15
0
 def setUp(self):
     # Open the page
     self.driver = WebDriver()
     self.driver.implicitly_wait(5)
     self.driver.set_window_size(1024, 768)
     self.driver.get(self.live_server_url)
     TestCase.setUp(self)
Пример #16
0
 def setUp(self):
     TestCase.setUp(self)
     for i in range(settings.OUR_COMPANY_ID + 3):
         u = User(username='******' % i, last_name='Mr. %i' % i,
                  first_name='TJ', password='******')
         u.save()
         CompanyInfo(town='town%i' % i, phone=(1000 + i), user=u).save()
     self._insertInvoice('socks')
Пример #17
0
    def __init__(self, *args, **kwargs):
        TestCase.__init__(self)

        # _testMethodName is a name of a method to test by a test runner
        self._testMethodName = 'run_simulation'

        self.logger = SimulationLogger(path_pattern=self.log_path_pattern)
        self.prepare(*args, **kwargs)
Пример #18
0
 def setUpClass(cls):
     TestCase.setUpClass()
     cls.dirname = tempfile.mkdtemp()
     cls.pki = PKI(dirname=cls.dirname)
     cls.ca_entry = CertificateEntry('test_CA', organizationName='test_org', organizationalUnitName='test_unit',
                                     emailAddress='*****@*****.**', localityName='City',
                                     countryName='FR', stateOrProvinceName='Province', altNames=[],
                                     role=CA_TEST, dirname=cls.dirname)
Пример #19
0
 def setUp(self):
     """
     ready up all variables and test class
     """
     TestCase.setUp(self)
     print '=' * 100
     print "<%s> currently run: %s" % (self.__class__.__name__, self._testMethodName)
     print '-' * 100 + '\n'
 def setUp(self):
     TestCase.setUp(self)
     self.brand = Brand(self)
     self.system = System(self)
     BaseTestCase.setUp(self)
     self.create_user(username='******', email='*****@*****.**', password='******', is_superuser=True)
     self.brand.send_container_tracker_feed()
     self.access_token = self.brand.admin_login()
Пример #21
0
 def setUpClass(cls):
     TestCase.setUpClass()
     pki = PKI()
     pki.initialize()
     entry = CertificateEntry(cls.domain_name, organizationalUnitName='certificates', emailAddress=settings.PENATES_EMAIL_ADDRESS,
                              localityName=settings.PENATES_LOCALITY, countryName=settings.PENATES_COUNTRY, stateOrProvinceName=settings.PENATES_STATE,
                              altNames=[], role=CA)
     pki.ensure_ca(entry)
Пример #22
0
    def __init__(self, *args, **kwargs):

        TestCase.__init__(self, *args, **kwargs)

        sample = os.path.join(
            settings.BASE_DIR, "interactions", "tests", "sample.mail")

        with open(sample, "rb") as f:
            self.sample = f.read()
Пример #23
0
    def setUp(self):
        TestCase.setUp(self)

        User.objects.create_superuser('root', '[email protected]', '123456')
        self.client.login(username='******', password='******')

        print '.' * 100
        print "<%s> currently run: %s" % (self.__class__.__name__, self._testMethodName)
        print '.' * 100 + '\n'
Пример #24
0
 def setUpClass(cls):
     """
     Delete the existing modulestores, causing them to be reloaded.
     """
     # Clear out any existing modulestores,
     # which will cause them to be re-created
     # the next time they are accessed.
     clear_existing_modulestores()
     TestCase.setUpClass()
Пример #25
0
    def setUp(self):
        settings.WSTOREMAIL = '*****@*****.**'
        settings.RSS = 'http://testhost.com/rssHost/'
        settings.STORE_NAME = 'wstore'

        # Create Mocks
        self.manager = model_manager.ModelManager({})
        self.manager._make_request = MagicMock()
        TestCase.setUp(self)
Пример #26
0
    def __init__(self, *args, **kwargs):

        TestCase.__init__(self, *args, **kwargs)
        self.sample = os.path.join(
            settings.BASE_DIR,
            "documents",
            "tests",
            "samples",
            "mail.txt"
        )
Пример #27
0
	def __init__(self, user, view_perms, read_perms, post_perms, new_thread_perms, view_group=[], read_group=[], post_group=[], new_thread_group=[]):
		self.view_perms, self.read_perms, self.post_perms, \
		self.new_thread_perms, self.view_group, self.read_group,\
		self.post_group, self.new_thread_group = view_perms, \
		read_perms, post_perms, new_thread_perms, \
		view_group, read_group, post_group, \
		new_thread_group
		self.password = '******'
		self.test_user = user
		TestCase.__init__(self)
Пример #28
0
    def setUp(self):
        TestCase.setUp(self)
        files = [find_first_fixture(f) for f in self.kbfixtures]

        fourstore_setup(self.kbname)
        fourstore_backend(self.kbname)
        fourstore_import(self.kbname, files)
        fourstore_httpd(self.kbname, self.port)

        settings.SPARQL_ENDPOINT = "http://localhost:%d/sparql/" % self.port
 def setUp(self):
     TestCase.setUp(self)
     BaseTestCase.setUp(self)
     self.brand = Brand(self)
     self.system = System(self)
     self.PHONE_NUMBER = "+TS0000000000"
     self.VALID_BRAND_ID = {
         'text': "BRAND BRAND001", 'phoneNumber': self.PHONE_NUMBER}
     self.INVALID_BRAND_ID = {
         'text': "BRAND BRAN", 'phoneNumber': self.PHONE_NUMBER}
Пример #30
0
 def test_create_duplicate_publisher(self):
     response = self.client.post(
         '/submissions/publisher/add/?wp_file=__all', {
             "publisher": "Azimov's",
             "web_address":
             "http://www.asimovs.com/contact-us/writers-guidelines/",
             "min_words": 1000,
             "max_words": 20000,
             "remarks": "Azimov's wants stories with some literary merit."
         },
         follow=True)
     #         print(response.content)
     TC.assertContains(self,
                       response=response,
                       text='Publisher already exists')
Пример #31
0
def test_cannot_post_with_empty_fields(test_case: TestCase,
                                       url: str,
                                       fields: List[str]):
    """Check if POST requests to url with missing data fields
    return 400 response code."""

    # Check post request with no data.
    response = test_case.client.post(url, data={})
    test_case.assertEqual(response.status_code, 400)

    # Check post request with only one field filled.
    if len(fields) > 1:
        for field in fields:
            response = test_case.client.post(url, data={field: 'test'})
            test_case.assertEqual(response.status_code, 400)
Пример #32
0
 def setUp(self):
     TestCase.setUp(self)
     self.partner_id = 1234
     self.secret = 'Secret'
     self.account = KalturaAccount.objects.create(
         team=TeamFactory(), partner_id=self.partner_id, secret=self.secret)
     self.entry_id = 'EntryId'
     url = ('http://cdnbakmi.kaltura.com'
            '/p/1492321/sp/149232100/serveFlavor/entryId/'
            '%s/flavorId/1_dqgopb2z/name/video.mp4') % self.entry_id
     self.video = VideoFactory(video_url__url=url, video_url__type='K')
     self.video_url = self.video.get_primary_videourl_obj()
     self.version = pipeline.add_subtitles(self.video, 'en',
                                           [(100, 200, "sub 1")])
     self.language = self.version.subtitle_language
Пример #33
0
def test_num_sources(testcase: TestCase, sources: pd.DataFrame, num: int):
    '''
    Test the number of overall sources identified is correct.

    Parameters
    ----------
    testcase : class
        Test class.
    sources : pd.DataFrame
        Dataframe containing identified sources.
    num : int
        Number of identified sources.
    '''

    testcase.assertEqual(len(sources.index), num)
Пример #34
0
    def tearDownClass(cls):
        """
        Drop the existing modulestores, causing them to be reloaded.
        Clean up any data stored in Mongo.
        """
        # Clean up by flushing the Mongo modulestore
        cls.drop_mongo_collections()

        # Clear out the existing modulestores,
        # which will cause them to be re-created
        # the next time they are accessed.
        # We do this at *both* setup and teardown just to be safe.
        clear_existing_modulestores()

        TestCase.tearDownClass()
Пример #35
0
    def __init__(self, purpose_price, users):
        self.test_case = TestCase()
        self.purpose_price = purpose_price

        def create_account(number):
            account = Account(user=User.objects.create_user(
                get_username(number), '*****@*****.**', 'qwerty12'))
            account.save()
            return account

        for key in users:
            create_account(key)
        Funds.objects.create(owner=get_account(1),
                             purpose='TestParty',
                             purpose_price=self.purpose_price)
Пример #36
0
 def addSkip(self, test: TestCase, reason: str) -> None:
     TestResult.addSkip(self, test, reason)
     self.stream.writeln(
         "** Skipping {}: {}".
         format(  # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139
             test.id(), reason))
     self.stream.flush()
Пример #37
0
 def test_modifyCourseCredits_CourseNotExist(self):
     """
         Test attempts to modify the number of credits
         a course that does not exist, and then verifies
         that the course still does not exist
     """
     myCourse = self.myCourseCatalog.searchCoursesThroughPartialName(
         "COEN 341")
     TestCase.assertEqual(self, len(myCourse), 0,
                          "The course exists already")
     self.myCourseCatalog.modifyCreditsForCourse("COEN", 341, 5)
     myCourse = self.myCourseCatalog.searchCoursesThroughPartialName(
         "COEN 341")
     TestCase.assertEqual(
         self, len(myCourse), 0,
         "The course has been added from an attempt to modify credits")
Пример #38
0
 def test_has_perm_unsupported_model(self):
     # Unsupported permission codename will raise PermissionNameError.
     user = self.factory.make_user()
     auth = PermissionAuth(user)
     with TestCase.assertRaises(self, PermissionNameError):
         GroupDevicePermission.objects.assign_perm("change_group",
                                                   self.group, self.device)
Пример #39
0
 def test_removeLecture_noLectureExists(self):
     """
         Test attempts to remove a non-existing lecture
         from a course and verifies that it is not there.
     """
     TestCase.assertFalse(
         self,
         self.myCourseCatalog.removeLectureFromCourse(
             "A", "SOEN", 341, "Fall"),
         "The non-existant lecture was successfully removed")
     TestCase.assertEqual(
         self,
         len(
             self.myCourseCatalog.searchCoursesThroughPartialName("SOEN341")
             [0].lecture_set.all()), 0,
         "The lecture was created and not removed")
Пример #40
0
def test_forced_num(testcase: TestCase, forced: dict, num: int):
    '''
    Test the number of forced extractions is expected.

    Parameters
    ----------
    testcase : class
        Test class.
    forced : dict
        The forced measurements.
    num : int
        The number of expected forced measurements.
    '''
    count = np.sum([len(f.index) for f in forced.values()])

    testcase.assertEqual(count, num)
Пример #41
0
 def test_basic_download(self):
     client = APIClient()
     p = client.get('http://127.0.0.1/liquid-dl/youtubedl-get-formats', {
         u'url':
         u'https://www.youtube.com/playlist?list=PLBML8SXyfQ6f0HYiKTs3riLBTaQfO-sGz',
         u'output_path': u'C:/tmp/toot',
         u'make_folder': u'false',
         u'new_folder_name': u'toot',
         u'is_playlist': u'false'
     },
                    format='json')
     self.assertIsInstance(p, JsonResponse)
     TestCase.assertContains(
         self,
         response=p,
         text="{\"success\": \"Downloaded Files successfully\"}")
Пример #42
0
def test_recordeditview_post_submit(client_admin, mock_create_record,
                                    mock_delete_record, record_data,
                                    signed_record_data):
    record_data['rtype'] = 'AAAA'
    response = client_admin.post(reverse('zoneeditor:zone_record_edit',
                                         kwargs={'zone': 'example.com.'}),
                                 data={
                                     'identifier': signed_record_data,
                                     **record_data
                                 })
    TestCase().assertRedirects(response,
                               '/zones/example.com.',
                               fetch_redirect_response=False)
    mock_delete_record.assert_called_once_with(
        zone='example.com.',
        name='mail.example.com.',
        rtype='MX',
        content='0 example.org.',
    )
    mock_create_record.assert_called_once_with(
        zone='example.com.',
        name='mail.example.com.',
        rtype='AAAA',
        ttl=300,
        content='0 example.org.',
    )
Пример #43
0
def test_zonedeleteview_post_no_confirm(client_admin, mock_pdns_delete_zone, signed_example_com):
    response = client_admin.post(reverse('zoneeditor:zone_delete'), data={
        'identifier': signed_example_com,
        'confirm': 'false',
    })
    TestCase().assertRedirects(response, '/zones', fetch_redirect_response=False)
    mock_pdns_delete_zone.assert_not_called()
Пример #44
0
def _django_db_fixture_helper(transactional, request, _django_cursor_wrapper):
    if is_django_unittest(request.node):
        return

    if transactional:
        _django_cursor_wrapper.enable()

        def flushdb():
            """Flush the database and close database connections"""
            # Django does this by default *before* each test
            # instead of after.
            from django.db import connections
            from django.core.management import call_command

            for db in connections:
                call_command('flush', verbosity=0,
                             interactive=False, database=db)
            for conn in connections.all():
                conn.close()

        request.addfinalizer(_django_cursor_wrapper.disable)
        request.addfinalizer(flushdb)
    else:
        if 'live_server' in request.funcargnames:
            return
        from django.test import TestCase

        _django_cursor_wrapper.enable()
        _django_cursor_wrapper._is_transactional = False
        case = TestCase(methodName='__init__')
        case._pre_setup()
        request.addfinalizer(_django_cursor_wrapper.disable)
        request.addfinalizer(case._post_teardown)
Пример #45
0
def _run_test(serializer_cls, model_cls, sql_queries=1, *,
              excluded_fields=None,
              extra_select_fields=None,
              extra_prefetch_fields=None, ) -> ReturnList:
    """
    Boilerplate for running the tests
    :return: the serializer data to assert one
    """

    print(
        f'Running test with serializer "{serializer_cls.__name__}" and model {model_cls.__name__}'
    )
    case = TestCase()
    request = APIRequestFactory().get("/FOO")

    with case.assertNumQueries(sql_queries):
        print(excluded_fields, extra_select_fields, extra_prefetch_fields)
        prefetched_queryset = prefetch(model_cls.objects.all(), serializer_cls, excluded_fields=excluded_fields,
                                       extra_select_fields=extra_select_fields,
                                       extra_prefetch_fields=extra_prefetch_fields)
        serializer_instance = serializer_cls(
            instance=prefetched_queryset, many=True, context={"request": request}
        )
        print("Data returned:")
        pprint_result(serializer_instance.data)
        return serializer_instance.data
Пример #46
0
 def setUpClass(cls):
     TestCase.setUpClass()
     cls.dirname = tempfile.mkdtemp()
     cls.pki = PKI(dirname=cls.dirname)
     cls.ca_entry = CertificateEntry('test_CA',
                                     organizationName='test_org',
                                     organizationalUnitName='test_unit',
                                     emailAddress='*****@*****.**',
                                     localityName='City',
                                     countryName='FR',
                                     stateOrProvinceName='Province',
                                     altNames=[],
                                     role=CA_TEST,
                                     dirname=cls.dirname)
     cls.pki.initialize()
     cls.pki.ensure_ca(cls.ca_entry)
     cls.tmp_filenames = []
Пример #47
0
def run_test(test: TestCase, result: TestResult) -> bool:
    failed = False
    test_method = get_test_method(test)

    if fast_tests_only() and is_known_slow_test(test_method):
        return failed

    test_name = full_test_name(test)

    bounce_key_prefix_for_testing(test_name)
    bounce_redis_key_prefix_for_testing(test_name)

    flush_caches_for_testing()

    if not hasattr(test, "_pre_setup"):
        # We are supposed to get here only when running a single test suite
        # on Python 3.5 or higher (the old import failure prefix is being
        # checked just in case). When running several test suites at once,
        # all import failures should be caught in deserialize_suite.
        import_failure_prefix_old = 'unittest.loader.ModuleImportFailure.'
        import_failure_prefix_new = 'unittest.loader._FailedTest.'
        if test_name.startswith(import_failure_prefix_old):
            actual_test_name = test_name[len(import_failure_prefix_old):]
            raise TestSuiteImportError(test_name=actual_test_name)

        elif test_name.startswith(import_failure_prefix_new):
            actual_test_name = test_name[len(import_failure_prefix_new):]
            raise TestSuiteImportError(test_name=actual_test_name)
        else:
            msg = "Test doesn't have _pre_setup; something is wrong."
            error_pre_setup = (Exception, Exception(msg), None)  # type: Tuple[Any, Any, Any]
            result.addError(test, error_pre_setup)
            return True
    test._pre_setup()

    start_time = time.time()

    test(result)  # unittest will handle skipping, error, failure and success.

    delay = time.time() - start_time
    enforce_timely_test_completion(test_method, test_name, delay, result)
    slowness_reason = getattr(test_method, 'slowness_reason', '')
    TEST_TIMINGS.append((delay, test_name, slowness_reason))

    test._post_teardown()
    return failed
Пример #48
0
 def test_removeTutorial(self):
     """
         Test adds a lecture to a course, and then a tutorial
         to that lecture, and then verifies that it is in the
         database, and then removes it and verifies that it is
         no long in the database
     """
     self.test_addTutorial()
     TestCase.assertTrue(
         self,
         self.myCourseCatalog.removeTutorialFromCourse(
             "AI", "SOEN", 341, "Fall"), "Tutorial removal not successful")
     TestCase.assertEqual(
         self,
         len(
             self.myCourseCatalog.searchCoursesThroughPartialName("SOEN341")
             [0].tutorial_set.all()), 0, "Tutorial not removed from course")
Пример #49
0
 def test_addTutorial_lectureNotExists(self):
     """
         Test attempts to add a tutorial to a course that
         doesn't exist and verifies that it is not found
         in the database.
     """
     TestCase.assertFalse(
         self,
         self.myCourseCatalog.addTutorialToCourse("AI", "COEN", 341, "Fall",
                                                  "8:45:00", "10:00:00",
                                                  "--W-F--", "SGW H-620",
                                                  "A"),
         "Tutorial successfully added to a course that does not exist")
     TestCase.assertEqual(
         self,
         len(self.myCourseCatalog.searchCoursesThroughPartialName(
             "COEN341")), 0, "Course has been added to database")
Пример #50
0
def djasserts():
    from django.test import TestCase
    testcase = TestCase()

    class Asserts:
        redirects = testcase.assertRedirects

    return Asserts()
Пример #51
0
def dj_asserts():
    from django.test import TestCase
    testcase = TestCase()

    class Asserts:
        html_equal = testcase.assertHTMLEqual

    return Asserts()
Пример #52
0
def test_inc_assoc(testcase: TestCase, ass_add: pd.DataFrame,
                   ass_backup: pd.DataFrame):
    '''
    Test that the number of associations increased or equal with added 
    images.

    Parameters
    ----------
    testcase : class
        Test class.
    ass_add : pd.DataFrame
        Associations after images were added.
    ass_backup : pd.DataFrame
        Associations before images were added.
    '''

    testcase.assertTrue(len(ass_add) >= len(ass_backup))
Пример #53
0
def test_zonedeleteview_post_granted(client, mock_pdns_delete_zone, zone_data, db_zone):
    assert Zone.objects.filter(name='example.com.').exists()
    response = client.post(reverse('zoneeditor:zone_delete'), data={
        'identifier': zone_data,
        'confirm': 'true',
    })
    TestCase().assertRedirects(response, '/zones', fetch_redirect_response=False)
    mock_pdns_delete_zone.assert_called_once_with('example.com.')
    assert not Zone.objects.filter(name='example.com.').exists()
Пример #54
0
 def setUp(self):
     TestCase.setUp(self)
     # Create group and some hints for it
     self.g1, self.g2 = mommy.make('timetable.Group',
                                   size=20), mommy.make('timetable.Group',
                                                        size=5)
     methods1 = [('1', 0), ('2', 10), ('3', 12)]
     methods2 = [('1', 0), ('2', 0), ('3', 0)]
     for method_name, size in methods1:
         mommy.make('friprosveta.GroupSizeHint',
                    group=self.g1,
                    size=size,
                    method=method_name)
     for method_name, size in methods2:
         mommy.make('friprosveta.GroupSizeHint',
                    group=self.g2,
                    size=size,
                    method=method_name)
Пример #55
0
 def test_addLecture(self):
     """
         Test attempts to add a lecture to a course
         and verifies that it is found in the database.
     """
     TestCase.assertTrue(
         self,
         self.myCourseCatalog.addLectureToCourse("A", "SOEN", 341,
                                                 "8:45:00", "10:00:00",
                                                 "--W-F--", "Fall",
                                                 "SGW H-620", False),
         "Lecture not successfully added to course")
     TestCase.assertEqual(
         self,
         len(
             self.myCourseCatalog.searchCoursesThroughPartialName("SOEN341")
             [0].lecture_set.all()), 1,
         "Lecture not successfully added to database")
Пример #56
0
    def setUpClass(cls):
        """
        Flush the mongo store and set up templates.
        """

        # Use a uuid to differentiate
        # the mongo collections on jenkins.
        cls.orig_modulestore = copy.deepcopy(settings.MODULESTORE)
        if 'direct' not in settings.MODULESTORE:
            settings.MODULESTORE['direct'] = settings.MODULESTORE['default']

        settings.MODULESTORE['default']['OPTIONS']['collection'] = 'modulestore_%s' % uuid4().hex
        settings.MODULESTORE['direct']['OPTIONS']['collection'] = 'modulestore_%s' % uuid4().hex
        xmodule.modulestore.django._MODULESTORES.clear()

        print settings.MODULESTORE

        TestCase.setUpClass()
Пример #57
0
    def setUp( self ):
        self.write_message_url = reverse( 'write_message' )
        self.get_all_messages_url = reverse( 'get_all_messages' )
        self.get_all_unread_messages_url = reverse( 'get_all_unread_messages' )
        self.read_message_url = reverse( "read_message" )
        self.delete_message_url = reverse( "delete_message" )
        TestCase.setUp( self )
        self.client_user = {}
        for username, password in {"client1":"client1", "client2":"client2", "client3":"client3"}.items():
            client, user = self.create_user_and_login( username, password )
            self.client_user[username] = {"client":client, "user":user, "msg_ids":[]}

        self.write_msg_from_sender_to_receiver( sender=self.client_user["client1"]["client"],
                                                receiver=self.client_user["client2"]["user"].username )
        self.write_msg_from_sender_to_receiver( sender=self.client_user["client2"]["client"],
                                                receiver=self.client_user["client3"]["user"].username )
        self.write_msg_from_sender_to_receiver( sender=self.client_user["client1"]["client"],
                                                receiver=self.client_user["client3"]["user"].username )
Пример #58
0
    def setUpClass(cls):
        TestCase.setUpClass()
        cls.domain = Domain.objects.get_or_create(name=cls.domain_name)[0]
        d = cls.domain.name

        # ok
        Record(domain=cls.domain, type='A', content=cls.ip,
               name='a.%s' % d).save()
        Record(domain=cls.domain,
               type='CNAME',
               content='a.%s' % d,
               name='b.%s' % d).save()
        Record(domain=cls.domain,
               type='CNAME',
               content='b.%s' % d,
               name='c.%s' % d).save()
        Record(domain=cls.domain,
               type='CNAME',
               content='c.%s' % d,
               name='d.%s' % d).save()
        Record(domain=cls.domain,
               type='CNAME',
               content='d.%s' % d,
               name='e.%s' % d).save()

        # loop
        Record(domain=cls.domain,
               type='CNAME',
               content='g.%s' % d,
               name='f.%s' % d).save()
        Record(domain=cls.domain,
               type='CNAME',
               content='h.%s' % d,
               name='g.%s' % d).save()
        Record(domain=cls.domain,
               type='CNAME',
               content='f.%s' % d,
               name='h.%s' % d).save()

        # no answer
        Record(domain=cls.domain,
               type='CNAME',
               content='j.%s' % d,
               name='i.%s' % d).save()
Пример #59
0
    def __init__(self, *args, **kwargs):

        # settings up HTTP authentification credentials

        try:
            username = settings.HTTP_TEST_USERNAME
            password = settings.HTTP_TEST_PASSWORD
        except AttributeError:
            raise Exception('You must define settings.HTTP_TEST_USERNAME '\
                            'and settings.HTTP_TEST_USERNAME to be able to '\
                            'test HTTP authentification')
        if not authenticate(username=username, password=password):
            raise Exception('settings.HTTP_TEST_USERNAME and '\
                            'settings.HTTP_TEST_PASSWORD are not valid '\
                            'credentials. Could not login.')

        auth = 'Basic %s' % base64.encodestring('%s:%s' % (username, password))
        self.auth = {'HTTP_AUTHORIZATION': auth.strip()}
        TestCase.__init__(self, *args, **kwargs)