Ejemplo n.º 1
0
 def setUp(self):
     """Setup user and account instances."""
     self.c = Client()
     self.user = User.objects.create_user(username="******",
                                          email="*****@*****.**",
                                          password="******")
     self.aws_account = AmazonDemoAccount(user=self.user)
Ejemplo n.º 2
0
 def setUp(self):
     """Setup user and account instances."""
     self.c = Client()
     self.user = User.objects.create_user(username="******",
                                          email="*****@*****.**",
                                          password="******")
     self.aws_account = AmazonDemoAccount(user=self.user)
Ejemplo n.º 3
0
class AWSTestCase(TestCase):
    """Test library app."""

    def setUp(self):
        """Setup user and account instances."""
        self.c = Client()
        self.user = User.objects.create_user(username="******",
                                             email="*****@*****.**",
                                             password="******")
        self.aws_account = AmazonDemoAccount(user=self.user)

    def test_validate_username(self):
        """Test validate username method."""
        # Test empty string
        self.aws_account.username = ''
        self.assertFalse(self.aws_account._validate_username())

        # Test name > 64
        self.aws_account.username = '******' * 65
        self.assertFalse(self.aws_account._validate_username())

        # Test valid string
        self.aws_account.username = '******'
        self.assertTrue(self.aws_account._validate_username())

        # Test invalid character
        self.aws_account.username = '******'
        self.assertFalse(self.aws_account._validate_username())

    def test_set_username(self):
        """Test set username method."""
        # Test unicode converts to ascii Jőhn to John
        with patch.object(AmazonAccountUtils,
                          'iam_user_exists',
                          return_value=False):
            self.aws_account._set_username()
            self.assertEqual(self.aws_account.username, 'John')

        # Test random username generated if iam user exists
        with patch.object(AmazonAccountUtils,
                          'iam_user_exists',
                          return_value=True):
            self.aws_account._set_username()
            self.assertNotEqual(self.aws_account.username, 'John')
            self.assertEqual(len(self.aws_account.username), 20)

        # Test random username is generated when regex invalid
        # after conversion. ʢʢʢ converts to ???.
        self.user.username = '******'
        self.aws_account._set_username()
        self.assertNotEqual(self.aws_account.username, '???')
        self.assertEqual(len(self.aws_account.username), 20)

    def test_aws_checkout(self):
        """Test AWS IAM checkout and checkin.

        Mock cleanup method with a return value of True.
        """
        self.c.login(username=self.user.username, password='******')
        mocker = AWSMock()
        mocker.create_group({'GroupName': 'Admins'})

        # Checkout AWS account
        with self.settings(AWS_ACCOUNT_ID_ALIAS='John.Wayne',
                           AWS_IAM_GROUPS=['Admins']):
            with patch('botocore.client.BaseClient._make_api_call',
                       new=mocker.mock_make_api_call):
                # Test check out AWS lendable
                response = self.c.get(reverse('library:checkout',
                                              args=['amazondemoaccount']),
                                      follow=True)

        # Get lendable and parse due date string
        aws_lendable = self.user.lendable_set.first()
        date_str = aws_lendable.due_on.strftime("%-d %b %Y").lower()

        # Confirm sucess message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual("'Amazon Web Services - Demo Account' "
                         "is checked out to you until %s." % date_str,
                         message)

        # Confirm credential values displayed in modal
        self.assertContains(response, '<code>John</code>')
        self.assertContains(response,
                            'https://John.Wayne.signin.aws.amazon.com/console')

        # Confirm lendable created
        self.assertEqual(Lendable.all_types.count(), 1)

        # Test user cannot checkout AWS account twice
        response = self.c.get(reverse('library:checkout',
                                      args=['amazondemoaccount']),
                              follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message,
                         "Amazon Web Services - Demo Account "
                         "unavailable for checkout.")

        # Confirm lendable not created
        self.assertEqual(Lendable.all_types.count(), 1)

        # Get lendable primary key
        pk = self.user.lendable_set.first().id

        # Test checkin handles generic exception
        with patch.object(AmazonDemoAccount,
                          'checkin',
                          side_effect=Exception('Checkin Failed!')):
            response = self.c.get(reverse('library:checkin',
                                          args=[pk]),
                                  follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message, 'Checkin Failed!')

        # Checkin AWS account
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            # Test check in AWS lendable
            response = self.c.get(reverse('library:checkin',
                                          args=[pk]),
                                  follow=True)

        # Confirm success message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual("'Amazon Web Services - Demo Account' returned.",
                         message)

        # Confirm lendable checked in and now has a check in date
        self.assertEqual(Lendable.all_types.count(), 0)
        self.assertIsNotNone(Lendable.all_lendables.first().checked_in_on)

        mocker.delete_group({'GroupName': 'Admins'})

    def test_checkout_group_exception(self):
        mocker = AWSMock()
        self.c.login(username=self.user.username, password='******')

        # Test create IAM account group not found exception handled
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            with self.settings(AWS_IAM_GROUPS=['Admins'],
                               AWS_ACCOUNT_ID_ALIAS=None):
                response = self.c.get(reverse('library:checkout',
                                              args=['amazondemoaccount']),
                                      follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message,
                         "An error occurred (Not Found) when calling the "
                         "AddUserToGroup operation: Group Admins not found")

        # Confirm lendable not created
        self.assertEqual(Lendable.all_types.count(), 0)

    def test_checkout_exception(self):
        """Test exception from create IAM account is handled properly."""
        mocker = AWSMock()
        self.user.username = fake_user_name
        self.user.save()

        self.c.login(username=self.user.username, password='******')

        # Test create IAM account exception handled
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            with patch.object(AmazonAccountUtils,
                              '_cleanup_iam_user',
                              return_value=True):
                response = self.c.get(reverse('library:checkout',
                                              args=['amazondemoaccount']),
                                      follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message,
                         "An error occurred (409) when calling the "
                         "CreateUser operation: User fakeuser exists")

        # Confirm lendable not created
        self.assertEqual(Lendable.all_types.count(), 0)

    def test_checkin_404(self):
        self.c.login(username=self.user.username, password='******')

        response = self.c.get(reverse('library:checkin',
                                      args=[1]),
                              follow=True)

        # Confirm 404 displayed
        self.assertEqual(response.status_code, 404)

    def test_destroy_account_not_exist(self):
        mocker = AWSMock()
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            amazon_account_utils = AmazonAccountUtils(
                '43543253245',
                '6543654rfdfds'
            )
            result = amazon_account_utils.destroy_iam_account('john')

        self.assertFalse(result)
Ejemplo n.º 4
0
class AWSTestCase(TestCase):
    """Test library app."""

    def setUp(self):
        """Setup user and account instances."""
        self.c = Client()
        self.user = User.objects.create_user(username="******",
                                             email="*****@*****.**",
                                             password="******")
        self.aws_account = AmazonDemoAccount(user=self.user)

    def test_validate_username(self):
        """Test validate username method."""
        # Test empty string
        self.aws_account.username = ''
        self.assertFalse(self.aws_account._validate_username())

        # Test name > 64
        self.aws_account.username = '******' * 65
        self.assertFalse(self.aws_account._validate_username())

        # Test valid string
        self.aws_account.username = '******'
        self.assertTrue(self.aws_account._validate_username())

        # Test invalid character
        self.aws_account.username = '******'
        self.assertFalse(self.aws_account._validate_username())

    def test_set_username(self):
        """Test set username method."""
        # Test unicode converts to ascii Jőhn to John
        with patch.object(AmazonAccountUtils,
                          'iam_user_exists',
                          return_value=False):
            self.aws_account._set_username()
            self.assertEqual(self.aws_account.username, 'John')

        # Test random username generated if iam user exists
        with patch.object(AmazonAccountUtils,
                          'iam_user_exists',
                          return_value=True):
            self.aws_account._set_username()
            self.assertNotEqual(self.aws_account.username, 'John')
            self.assertEqual(len(self.aws_account.username), 20)

        # Test random username is generated when regex invalid
        # after conversion. ʢʢʢ converts to ???.
        self.user.username = '******'
        self.aws_account._set_username()
        self.assertNotEqual(self.aws_account.username, '???')
        self.assertEqual(len(self.aws_account.username), 20)

    def test_aws_checkout(self):
        """Test AWS IAM checkout and checkin.

        Mock cleanup method with a return value of True.
        """
        self.c.login(username=self.user.username, password='******')
        mocker = AWSMock()
        mocker.create_group({'GroupName': 'Admins'})

        # Checkout AWS account
        with self.settings(AWS_ACCOUNT_ID_ALIAS='John.Wayne',
                           AWS_IAM_GROUP='Admins'):
            with patch('botocore.client.BaseClient._make_api_call',
                       new=mocker.mock_make_api_call):
                # Test check out AWS lendable
                response = self.c.get(reverse('library:checkout',
                                              args=['amazondemoaccount']),
                                      follow=True)

        # Get lendable and parse due date string
        aws_lendable = self.user.lendable_set.first()
        date_str = aws_lendable.due_on.strftime("%-d %b %Y").lower()

        # Confirm sucess message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual("'Amazon Web Services - Demo Account' "
                         "is checked out to you until %s." % date_str,
                         message)

        # Confirm credential values displayed in modal
        self.assertContains(response, '<code>John</code>')
        self.assertContains(response,
                            'https://John.Wayne.signin.aws.amazon.com/console')

        # Confirm lendable created
        self.assertEqual(Lendable.all_types.count(), 1)

        # Test user cannot checkout AWS account twice
        response = self.c.get(reverse('library:checkout',
                                      args=['amazondemoaccount']),
                              follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message,
                         "Amazon Web Services - Demo Account "
                         "unavailable for checkout.")

        # Confirm lendable not created
        self.assertEqual(Lendable.all_types.count(), 1)

        # Get lendable primary key
        pk = self.user.lendable_set.first().id

        # Test checkin handles generic exception
        with patch.object(AmazonDemoAccount,
                          'checkin',
                          side_effect=Exception('Checkin Failed!')):
            response = self.c.get(reverse('library:checkin',
                                          args=[pk]),
                                  follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message, 'Checkin Failed!')

        # Checkin AWS account
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            # Test check in AWS lendable
            response = self.c.get(reverse('library:checkin',
                                          args=[pk]),
                                  follow=True)

        # Confirm success message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual("'Amazon Web Services - Demo Account' returned.",
                         message)

        # Confirm lendable deleted
        self.assertEqual(Lendable.all_types.count(), 0)

        mocker.delete_group({'GroupName': 'Admins'})

    def test_checkout_group_exception(self):
        mocker = AWSMock()
        self.c.login(username=self.user.username, password='******')

        # Test create IAM account group not found exception handled
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            with self.settings(AWS_IAM_GROUP='Admins',
                               AWS_ACCOUNT_ID_ALIAS=None):
                response = self.c.get(reverse('library:checkout',
                                              args=['amazondemoaccount']),
                                      follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message,
                         "An error occurred (Not Found) when calling the "
                         "AddUserToGroup operation: Group Admins not found")

        # Confirm lendable not created
        self.assertEqual(Lendable.all_types.count(), 0)

    def test_checkout_exception(self):
        """Test exception from create IAM account is handled properly."""
        mocker = AWSMock()
        self.user.username = fake_user_name
        self.user.save()

        self.c.login(username=self.user.username, password='******')

        # Test create IAM account exception handled
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            with patch.object(AmazonAccountUtils,
                              '_cleanup_iam_user',
                              return_value=True):
                response = self.c.get(reverse('library:checkout',
                                              args=['amazondemoaccount']),
                                      follow=True)

        # Confirm error message displayed
        message = list(response.context['messages'])[0].message
        self.assertEqual(message,
                         "An error occurred (409) when calling the "
                         "CreateUser operation: User fakeuser exists")

        # Confirm lendable not created
        self.assertEqual(Lendable.all_types.count(), 0)

    def test_checkin_404(self):
        self.c.login(username=self.user.username, password='******')

        response = self.c.get(reverse('library:checkin',
                                      args=[1]),
                              follow=True)

        # Confirm 404 displayed
        self.assertEqual(response.status_code, 404)

    def test_destroy_account_not_exist(self):
        mocker = AWSMock()
        with patch('botocore.client.BaseClient._make_api_call',
                   new=mocker.mock_make_api_call):
            amazon_account_utils = AmazonAccountUtils(
                '43543253245',
                '6543654rfdfds'
            )
            result = amazon_account_utils.destroy_iam_account('john')

        self.assertFalse(result)