Ejemplo n.º 1
0
 def test_get_location_string_no_city_no_country(self):
     """Does get_location_string() work when there's no city or country?"""
     with testfixtures.Replacer() as r:
         r.replace('stars.apps.institutions.models.Institution.profile',
                   MockProfile(city='', state='ST', country_iso=''))
         institution = InstitutionFactory()
         self.assertEqual(institution.get_location_string(), 'ST')
Ejemplo n.º 2
0
    def test_form_valid_starts_migration(self):
        """When all is ok, is a migration task started?
        """
        if self.migration_task_name:
            # only run in subclass where attributes are set.
            self.account.user_level = 'admin'
            self.account.save()
            self.request.method = 'POST'
            self.request.POST = {'is_locked': True}

            class migrationTask(object):
                def delay(self, *args, **kwargs):
                    return 1 / 0

            with testfixtures.Replacer() as r:
                self.open_gate()
                # stub out the migration function with a lambda that'll
                # raise a ZeroDivisionError, then we can check to
                # see if that error's raised when the migration
                # function should be called.
                r.replace(
                    'stars.apps.tool.manage.views.' + self.migration_task_name,
                    migrationTask())
                self.assertRaises(ZeroDivisionError,
                                  self.view_class.as_view(),
                                  self.request,
                                  institution_slug=self.institution.slug,
                                  pk=self._get_pk())
 def test_poll(self):
     stream = PiecewiseStream(b'alpha beta gamma omega', max_chunk=5)
     with testfixtures.Replacer() as r:
         mock_time = testfixtures.test_time(delta=0.1, delta_type='seconds')
         r.replace('streamexpect.time.time', mock_time)
         adapter = PollingStreamAdapter(stream)
         for chunk in (b'alpha', b' beta', b' gamm', b'a ome'):
             self.assertEqual(chunk, adapter.poll(1.0))
 def test_timeout(self):
     with testfixtures.Replacer() as r:
         mock_time = testfixtures.test_time(delta=0.1, delta_type='seconds')
         r.replace('streamexpect.time.time', mock_time)
         r.replace('streamexpect.time.sleep', lambda _: None)
         stream = EmptyStream()
         adapter = PollingStreamAdapter(stream)
         with self.assertRaises(ExpectTimeout):
             adapter.poll(1)
Ejemplo n.º 5
0
def popen_mock_command():
    """Fixture for adding a command with specified output and return to the popen mock."""
    replacer = testfixtures.Replacer()
    popen = testfixtures.popen.MockPopen()

    def add_command(cmd, stdout=b"", stderr=b"", returncode=0):
        popen.set_command(cmd, stdout, stderr, returncode)
        replacer.replace("subprocess.Popen", popen)
        # return popen

    yield add_command
    replacer.restore()
 def test_timeout(self):
     source, drain = socket.socketpair()
     try:
         with testfixtures.Replacer() as r:
             mock_time = testfixtures.test_time(delta=0.1,
                                                delta_type='seconds')
             r.replace('streamexpect.time.time', mock_time)
             adapter = PollingSocketStreamAdapter(drain)
             with self.assertRaises(ExpectTimeout):
                 adapter.poll(0.01)
     finally:
         source.close()
         drain.close()
 def test_poll(self):
     source, drain = socket.socketpair()
     try:
         with testfixtures.Replacer() as r:
             mock_time = testfixtures.test_time(delta=0.1,
                                                delta_type='seconds')
             r.replace('streamexpect.time.time', mock_time)
             adapter = PollingSocketStreamAdapter(drain)
             for chunk in (b'alpha', b' beta', b' gamm', b'a ome'):
                 source.send(chunk)
                 self.assertEqual(chunk, adapter.poll(1.0))
     finally:
         source.close()
         drain.close()
Ejemplo n.º 8
0
    def test_compress_warning_logging(self):
        """Does compress log a warning message if data might be lost?
        """
        cwos = ChoiceWithOtherSubmission()
        with testfixtures.LogCapture('stars') as log:
            with testfixtures.Replacer() as r:
                r.replace(
                    'stars.apps.submissions.models.ChoiceWithOtherSubmission.'
                    'get_last_choice', lambda x: MockChoice())
                cwos.compress(choice='yellow', other_value=True)

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].levelname, 'WARNING')
        self.assertTrue('will not be saved because' in log.records[0].msg)
    def test_compress_warning_logging(self):
        """Does compress log a warning message if data might be lost?
        """
        mcwos = MultiChoiceWithOtherSubmission()
        with testfixtures.LogCapture('stars') as log:
            with testfixtures.Replacer() as r:
                r.replace(
                    'stars.apps.submissions.models.'
                    'MultiChoiceWithOtherSubmission.get_last_choice', lambda x:
                    Choice(id=-88888, is_bonafide=False, choice='green'))
                mcwos.compress(choices=['yellow'], other_value=True)

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].levelname, 'WARNING')
        self.assertTrue('will not be saved because' in log.records[0].msg)
Ejemplo n.º 10
0
    def test_update_from_iss_logging(self):
        """Does update_from_iss log a warning if there's no ISS instituion?
        """
        institution = Institution()
        institution.name = 'bob'

        with testfixtures.LogCapture('stars') as log:
            with testfixtures.Replacer() as r:
                r.replace('stars.apps.institutions.models.Institution.profile',
                          None)
                institution.update_from_iss()

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].levelname, 'WARNING')
        self.assertTrue('No ISS institution found bob' in log.records[0].msg)
Ejemplo n.º 11
0
 def test_process_form_invalid_form_error_message(self):
     """Does process_form show an error message if a form is invalid?
     """
     with testfixtures.Replacer() as r:
         r.replace('stars.apps.helpers.forms.views.FormActionView.get_form',
                   lambda x, y, z: MockForm())
         views.FormActionView(None, None).process_form(request=self.request,
                                                       context={})
     response = render(self.request, 'base.html')
     soup = BeautifulSoup(response.content)
     error_message_divs = soup.find_all(
         'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]})
     self.assertEqual(len(error_message_divs), 1)
     self.assertTrue(
         'lease correct the errors' in error_message_divs[0].text)
Ejemplo n.º 12
0
 def test_save_new_form_rows_invalid_form_error_message(self):
     """Does save_new_form_rows show an error msg when a form is invalid?
     """
     with testfixtures.Replacer() as r:
         r.replace('stars.apps.helpers.forms.forms.HiddenCounterForm',
                   MockInvalidForm)
         form_helpers.save_new_form_rows(request=self.request,
                                         prefix=None,
                                         form_class=MockInvalidForm,
                                         instance_class=MockObject)
     response = render(self.request, 'base.html')
     soup = BeautifulSoup(response.content)
     error_message_divs = soup.find_all(
         'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]})
     self.assertEqual(len(error_message_divs), 1)
     self.assertTrue(
         MockInvalidForm.COUNTER_MESSAGE in error_message_divs[0].text)
Ejemplo n.º 13
0
 def test_confirm_unlock_form_success_message(self):
     """Does confirm_unlock_form show a success message upon unlocking?
     """
     MODEL_LABEL = 'buick century'
     with testfixtures.Replacer() as r:
         r.replace('stars.apps.helpers.forms.form_helpers.confirm_form',
                   lambda x, y: (None, True))
         r.replace('stars.apps.helpers.forms.form_helpers._get_model_label',
                   lambda x: MODEL_LABEL)
         form_helpers.confirm_unlock_form(self.request, MockObject())
     response = render(self.request, 'base.html')
     soup = BeautifulSoup(response.content)
     success_message_divs = soup.find_all(
         'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]})
     self.assertEqual(len(success_message_divs), 1)
     self.assertTrue(MODEL_LABEL
                     and 'was unlocked' in success_message_divs[0].text)
Ejemplo n.º 14
0
    def test_get_identifier_logging(self):
        """Does get_identifier log an error when there's no identifier?
        """
        credit = Credit()
        with testfixtures.LogCapture('stars') as log:
            with testfixtures.Replacer() as r:
                r.replace(
                    'stars.apps.credits.models.Credit.subcategory',
                    MockSubcategory(MockCategory(MockCreditset())),
                )
                r.replace(
                    'stars.apps.credits.models.Credit.get_1_0_identifier',
                    lambda x: True)
                credit.get_identifier()

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].levelname, 'ERROR')
        self.assertTrue('No identifier' in log.records[0].msg)
Ejemplo n.º 15
0
    def test_set_slug_from_iss_institution_logging(self):
        """Does set_slug_from_iss_institution log exceptions (as errors)?
        """
        institution = Institution()

        def raiser(*args):
            raise Exception('bo-o-o-gus exception')

        with testfixtures.LogCapture('stars') as log:
            with testfixtures.Replacer() as r:
                r.replace('stars.apps.institutions.models.Institution.profile',
                          MockProfile())
                r.replace('stars.apps.institutions.models.slugify', raiser)
                institution.set_slug_from_iss_institution(-99999)

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].levelname, 'ERROR')
        self.assertTrue('set slug for' in log.records[0].msg)
Ejemplo n.º 16
0
 def test_save_new_form_rows_error_saving_error_message(self):
     """Does save_new_form_rows show an error msg when saving fails?
     """
     with testfixtures.Replacer() as r:
         r.replace('stars.apps.helpers.forms.forms.HiddenCounterForm',
                   MockValidForm)
         r.replace(
             'stars.apps.helpers.forms.form_helpers._perform_save_form',
             lambda w, x, y, z, show_message:
             (MockValidForm(), None, False))
         form_helpers.save_new_form_rows(request=self.request,
                                         prefix=None,
                                         form_class=MockValidForm,
                                         instance_class=MockObject)
     response = render(self.request, 'base.html')
     soup = BeautifulSoup(response.content)
     error_message_divs = soup.find_all(
         'div', {'class': settings.MESSAGE_TAGS[messages.ERROR]})
     self.assertEqual(len(error_message_divs), 1)
     self.assertTrue(
         MockValidForm.SAVE_ERROR_MESSAGE in error_message_divs[0].text)
Ejemplo n.º 17
0
 def test_save_new_form_rows_success_message(self):
     """Does save_new_form_rows show a success message when it succeeds?
     """
     with testfixtures.Replacer() as r:
         r.replace('stars.apps.helpers.forms.forms.HiddenCounterForm',
                   MockValidForm)
         r.replace(
             'stars.apps.helpers.forms.form_helpers._perform_save_form',
             lambda w, x, y, z, show_message: (MockValidForm(), None, True))
         form_helpers.save_new_form_rows(request=self.request,
                                         prefix=None,
                                         form_class=MockValidForm,
                                         instance_class=MockValidForm)
     response = render(self.request, 'base.html')
     soup = BeautifulSoup(response.content)
     success_message_divs = soup.find_all(
         'div', {'class': settings.MESSAGE_TAGS[messages.SUCCESS]})
     self.assertEqual(len(success_message_divs), 1)
     self.assertTrue(
         '1 new'
         and 'were created successfully' in success_message_divs[0].text)
    def test_decompress_fake_choice_logging(self):
        """Does decompress log an error when the choice is not bonafide?
        """
        mcwos = MultiChoiceWithOtherSubmission()

        choices = [
            Choice(id=-99998, is_bonafide=False, choice=True),
            Choice(id=-99999, is_bonafide=False)
        ]
        with testfixtures.LogCapture('stars') as log:
            with testfixtures.Replacer() as r:
                r.replace('stars.apps.submissions.models.Choice',
                          MockChoiceModel(choices))
                r.replace(('stars.apps.submissions.models.'
                           'MultiChoiceWithOtherSubmission.get_last_choice'),
                          lambda x: choices[0])
                mcwos.decompress(value=[-99998, -99999])

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].levelname, 'ERROR')
        self.assertTrue(
            log.records[0].msg.startswith('Found multiple \'other\' choices'))