Example #1
0
    def test_should_return_identities_for_an_environment(self):
        client = self.set_up()

        # Given
        identifierOne = 'user1'
        identifierTwo = 'user2'
        organisation = Organisation(name='ssg')
        organisation.save()
        project = Project(name='project1', organisation=organisation)
        project.save()
        environment = Environment(name='environment1', project=project)
        environment.save()
        identityOne = Identity(identifier=identifierOne,
                               environment=environment)
        identityOne.save()
        identityTwo = Identity(identifier=identifierTwo,
                               environment=environment)
        identityTwo.save()
        # When
        response = client.get('/api/v1/environments/%s/identities/' %
                              environment.api_key)
        # Then
        self.assertEquals(response.data['results'][0]['identifier'],
                          identifierOne)
        self.assertEquals(response.data['results'][1]['identifier'],
                          identifierTwo)
Example #2
0
 def setUp(self):
     self.organisation = Organisation.objects.create(name="Test Org")
     self.project = Project.objects.create(name="Test Project", organisation=self.organisation)
     self.feature = Feature.objects.create(name="Test Feature", project=self.project)
     # The environment is initialised in a non-saved state as we want to test the save
     # functionality.
     self.environment = Environment(name="Test Environment", project=self.project)
Example #3
0
def addEnv(env):
    try:
        e = Environment.objects.get(name=env.name)
        if e.pk:
            msg("Env " + env.name + " already exists")
            return e
    except:
        pass
    msg("importing new env " + env.name)
    e = Environment(name=env.name, datacenter=dc)
    e.save()
    return e
Example #4
0
 def generate_database_models(identifier='user1'):
     organisation = Organisation(name='ssg')
     organisation.save()
     project = Project(name='project1', organisation=organisation)
     project.save()
     environment = Environment(name='environment1', project=project)
     environment.save()
     feature = Feature(name="feature1", project=project)
     feature.save()
     identity = Identity(identifier=identifier, environment=environment)
     identity.save()
     return identity, project
Example #5
0
def addEnv(env): 
    try:
        e = Environment.objects.get(name = env.name)
        if e.pk:
            msg("Env " + env.name + " already exists")
            return e
    except:
        pass
    msg("importing new env " + env.name)
    e = Environment(name = env.name, datacenter=dc)
    e.save()
    return e
Example #6
0
def track_request_influxdb(request):
    """
    Sends API event data to InfluxDB

    :param request: (HttpRequest) the request being made
    """
    resource = get_resource_from_uri(request.path)

    if resource and resource in TRACKED_RESOURCE_ACTIONS:
        environment = Environment.get_from_cache(
            request.headers.get("X-Environment-Key"))
        if environment is None:
            return

        tags = {
            "resource": resource,
            "organisation": environment.project.organisation.get_unique_slug(),
            "organisation_id": environment.project.organisation_id,
            "project": environment.project.name,
            "project_id": environment.project_id,
        }

        influxdb = InfluxDBWrapper("api_call")
        influxdb.add_data_point("request_count", 1, tags=tags)
        influxdb.write()
Example #7
0
 def create_ffadminuser():
     Helper.clean_up()
     organisation = Organisation(name='test org')
     organisation.save()
     project = Project(name="test project", organisation=organisation)
     project.save()
     environment = Environment(name="test env", project=project)
     environment.save()
     user = FFAdminUser(username="******",
                        email="*****@*****.**",
                        first_name="test",
                        last_name="user")
     user.set_password("testuser123")
     user.save()
     user.organisations.add(organisation)
     user.save()
     return user
Example #8
0
    def test_get_from_cache_returns_None_if_no_matching_environment(self):
        # Given
        api_key = "no-matching-env"

        # When
        env = Environment.get_from_cache(api_key)

        # Then
        assert env is None
    def authenticate(self, request):
        try:
            environment = Environment.get_from_cache(
                request.META.get('HTTP_X_ENVIRONMENT_KEY'))
        except Environment.DoesNotExist:
            raise exceptions.AuthenticationFailed(
                'Invalid or missing Environment Key')

        if not self._can_serve_flags(environment):
            raise exceptions.AuthenticationFailed(
                'Organisation is disabled from serving flags.')

        request.environment = environment
Example #10
0
    def authenticate(self, request):
        try:
            api_key = request.META.get("HTTP_X_ENVIRONMENT_KEY")
            environment = Environment.get_from_cache(api_key)
        except Environment.DoesNotExist:
            raise AuthenticationFailed("Invalid or missing Environment Key")

        if not self._can_serve_flags(environment):
            raise AuthenticationFailed("Organisation is disabled from serving flags.")

        request.environment = environment

        # DRF authentication expects a two tuple to be returned containing User, auth
        return None, None
Example #11
0
    def test_get_from_cache_stores_environment_in_cache_on_success(
            self, mock_cache):
        # Given
        self.environment.save()
        mock_cache.get.return_value = None

        # When
        environment = Environment.get_from_cache(self.environment.api_key)

        # Then
        assert environment == self.environment
        mock_cache.set.assert_called_with(self.environment.api_key,
                                          self.environment,
                                          timeout=60)
Example #12
0
def track_request_googleanalytics(request):
    """
    Utility function to track a request to the API with the specified URI

    :param request: (HttpRequest) the request being made
    """
    pageview_data = DEFAULT_DATA + "t=pageview&dp=" + quote(request.path, safe='')
    # send pageview request
    requests.post(GOOGLE_ANALYTICS_COLLECT_URL, data=pageview_data)

    resource = get_resource_from_uri(request.path)

    if resource in TRACKED_RESOURCE_ACTIONS:
        environment = Environment.get_from_cache(request.headers.get('X-Environment-Key'))
        track_event(environment.project.organisation.get_unique_slug(), resource)
Example #13
0
    def get(self, request):
        try:
            environment = Environment.get_environment_from_request(request)
        except EnvironmentHeaderNotPresentError:
            error = {"detail": "Environment Key header not provided"}
            return Response(error, status=status.HTTP_400_BAD_REQUEST)
        except ObjectDoesNotExist:
            error_response = {
                "error": "Environment not found for provided key"
            }
            return Response(error_response, status=status.HTTP_400_BAD_REQUEST)

        return Response(self.get_serializer(environment.project.segments.all(),
                                            many=True).data,
                        status=status.HTTP_200_OK)
Example #14
0
def track_request(request):
    """
    Utility function to track a request to the API with the specified URI

    :param request: (HttpRequest) the request being made
    """
    uri = request.path
    data = DEFAULT_DATA + "t=pageview&dp=" + quote(uri, safe='')
    requests.post(GOOGLE_ANALYTICS_COLLECT_URL, data=data)

    resource = uri.split('/')[
        3]  # uri will be in the form /api/v1/<resource>/...
    if resource in TRACKED_RESOURCE_ACTIONS:
        environment = Environment.get_from_cache(
            request.headers.get('X-Environment-Key'))
        track_event(environment.project.organisation.get_unique_slug(),
                    TRACKED_RESOURCE_ACTIONS[resource])
Example #15
0
def track_request_influxdb(request):
    """
    Sends API event data to InfluxDB

    :param request: (HttpRequest) the request being made
    """
    resource = get_resource_from_uri(request.path)

    if resource:
        environment = Environment.get_from_cache(
            request.headers.get('X-Environment-Key'))

        tags = {
            "resource": resource,
            "organisation": environment.project.organisation.get_unique_slug(),
            "organisation_id": environment.project.organisation_id,
            "project": environment.project.name,
            "project_id": environment.project_id
        }

        influxdb = InfluxDBWrapper("api_call", "request_count", 1, tags=tags)
        influxdb.write()
Example #16
0
class EnvironmentSaveTestCase(TestCase):
    def setUp(self):
        self.organisation = Organisation.objects.create(name="Test Org")
        self.project = Project.objects.create(name="Test Project",
                                              organisation=self.organisation)
        self.feature = Feature.objects.create(name="Test Feature",
                                              project=self.project)
        # The environment is initialised in a non-saved state as we want to test the save
        # functionality.
        self.environment = Environment(name="Test Environment",
                                       project=self.project)

    def test_environment_should_be_created_with_feature_states(self):
        # Given - set up data

        # When
        self.environment.save()

        # Then
        feature_states = FeatureState.objects.filter(
            environment=self.environment)
        assert hasattr(self.environment, "api_key")
        assert feature_states.count() == 1

    def test_on_creation_save_feature_states_get_created(self):
        # These should be no feature states before saving
        self.assertEqual(FeatureState.objects.count(), 0)

        self.environment.save()

        # On the first save a new feature state should be created
        self.assertEqual(FeatureState.objects.count(), 1)

    def test_on_update_save_feature_states_get_updated_not_created(self):
        self.environment.save()

        self.feature.default_enabled = True
        self.feature.save()
        self.environment.save()

        self.assertEqual(FeatureState.objects.count(), 1)

    def test_on_creation_save_feature_is_created_with_the_correct_default(
            self):
        self.environment.save()
        self.assertFalse(FeatureState.objects.get().enabled)

    def test_on_update_save_feature_gets_updated_with_the_correct_default(
            self):
        self.environment.save()
        self.assertFalse(FeatureState.objects.get().enabled)

        self.feature.default_enabled = True
        self.feature.save()

        self.assertTrue(FeatureState.objects.get().enabled)

    def test_on_update_save_feature_states_dont_get_updated_if_identity_present(
            self):
        self.environment.save()
        identity = Identity.objects.create(identifier="test-identity",
                                           environment=self.environment)

        fs = FeatureState.objects.get()
        fs.id = None
        fs.identity = identity
        fs.save()
        self.assertEqual(FeatureState.objects.count(), 2)

        self.feature.default_enabled = True
        self.feature.save()
        self.environment.save()
        fs.refresh_from_db()

        self.assertNotEqual(
            fs.enabled,
            FeatureState.objects.exclude(id=fs.id).get().enabled)
Example #17
0
    def test_should_delete_feature_states_when_feature_deleted(self):
        # Given
        client = self.set_up()
        organisation = Organisation.objects.get(name="test org")
        project = Project(name="test project", organisation=organisation)
        project.save()
        environment_1 = Environment(name="env 1", project=project)
        environment_2 = Environment(name="env 2", project=project)
        environment_3 = Environment(name="env 3", project=project)
        environment_1.save()
        environment_2.save()
        environment_3.save()
        client.post(self.project_features_url % project.id,
                    data=self.post_template %
                    ("test feature", project.id, "This is a value"),
                    content_type='application/json')
        feature = Feature.objects.get(name="test feature", project=project.id)

        # When
        response = client.delete(self.project_features_url % project.id,
                                 data='{"id": %d}' % feature.id,
                                 content_type='application/json')

        # Then
        self.assertEquals(response.status_code, status.HTTP_200_OK)
        # check feature was deleted succesfully
        self.assertEquals(
            0,
            Feature.objects.filter(name="test feature",
                                   project=project.id).count())
        # check feature was removed from all environments
        self.assertEquals(
            0,
            FeatureState.objects.filter(environment=environment_1,
                                        feature=feature).count())
        self.assertEquals(
            0,
            FeatureState.objects.filter(environment=environment_2,
                                        feature=feature).count())
        self.assertEquals(
            0,
            FeatureState.objects.filter(environment=environment_3,
                                        feature=feature).count())

        Helper.clean_up()
Example #18
0
    def test_should_create_feature_states_when_feature_created(self):
        # Given
        client = self.set_up()
        project = Project.objects.get(name="test project")
        environment_1 = Environment(name="env 1", project=project)
        environment_2 = Environment(name="env 2", project=project)
        environment_3 = Environment(name="env 3", project=project)
        environment_1.save()
        environment_2.save()
        environment_3.save()

        # When
        response = client.post(self.project_features_url % project.id,
                               data=self.post_template %
                               ("test feature", project.id, "This is a value"),
                               content_type='application/json')

        # Then
        self.assertEquals(response.status_code, status.HTTP_201_CREATED)
        # check feature was created successfully
        self.assertEquals(
            1,
            Feature.objects.filter(name="test feature",
                                   project=project.id).count())
        feature = Feature.objects.get(name="test feature", project=project.id)
        # check feature was added to all environments
        self.assertEquals(
            1,
            FeatureState.objects.filter(environment=environment_1,
                                        feature=feature).count())
        self.assertEquals(
            1,
            FeatureState.objects.filter(environment=environment_2,
                                        feature=feature).count())
        self.assertEquals(
            1,
            FeatureState.objects.filter(environment=environment_3,
                                        feature=feature).count())

        # check that value was correctly added to feature state
        feature_state = FeatureState.objects.get(environment=environment_1,
                                                 feature=feature)
        self.assertEquals("This is a value",
                          feature_state.get_feature_state_value())

        Helper.clean_up()
Example #19
0
class EnvironmentTestCase(TestCase):
    def setUp(self):
        self.organisation = Organisation.objects.create(name="Test Org")
        self.project = Project.objects.create(name="Test Project",
                                              organisation=self.organisation)
        self.feature = Feature.objects.create(name="Test Feature",
                                              project=self.project)
        # The environment is initialised in a non-saved state as we want to test the save
        # functionality.
        self.environment = Environment(name="Test Environment",
                                       project=self.project)

    def test_environment_should_be_created_with_feature_states(self):
        # Given - set up data

        # When
        self.environment.save()

        # Then
        feature_states = FeatureState.objects.filter(
            environment=self.environment)
        assert hasattr(self.environment, "api_key")
        assert feature_states.count() == 1

    def test_on_creation_save_feature_states_get_created(self):
        # These should be no feature states before saving
        self.assertEqual(FeatureState.objects.count(), 0)

        self.environment.save()

        # On the first save a new feature state should be created
        self.assertEqual(FeatureState.objects.count(), 1)

    def test_on_update_save_feature_states_get_updated_not_created(self):
        self.environment.save()

        self.feature.default_enabled = True
        self.feature.save()
        self.environment.save()

        self.assertEqual(FeatureState.objects.count(), 1)

    def test_on_creation_save_feature_is_created_with_the_correct_default(
            self):
        self.environment.save()
        self.assertFalse(FeatureState.objects.get().enabled)

    @mock.patch("environments.models.environment_cache")
    def test_get_from_cache_stores_environment_in_cache_on_success(
            self, mock_cache):
        # Given
        self.environment.save()
        mock_cache.get.return_value = None

        # When
        environment = Environment.get_from_cache(self.environment.api_key)

        # Then
        assert environment == self.environment
        mock_cache.set.assert_called_with(self.environment.api_key,
                                          self.environment,
                                          timeout=60)

    def test_get_from_cache_returns_None_if_no_matching_environment(self):
        # Given
        api_key = "no-matching-env"

        # When
        env = Environment.get_from_cache(api_key)

        # Then
        assert env is None