Exemple #1
0
    def _match(self, stats):
        expect(stats.summary).not_to(be_none)
        expect(stats.units).not_to(be_none)

        if stats.summary.min:
            expect(stats.summary.max).to(be_above_or_equal(stats.summary.min))

            # Work around jitter_ipdv stat, which can be negative
            if stats.summary.min > 0:
                expect(stats.summary.total).to(be_above(0))
                expect(stats.summary.max).to(be_above(0))
                if stats.summary.min != stats.summary.max:
                    expect(stats.summary.std_dev).to(be_above_or_equal(0))

        return True, ['is valid non zero summary statistic']
Exemple #2
0
    def _match(self, counters):
        expect(counters).to(be_a(client.models.PacketAnalyzerFlowCounters))
        expect(counters.frame_count).not_to(be_none)
        # Check optional summary statistics
        if counters.frame_count > 0:
            if counters.frame_length:
                expect(counters.frame_length).to(
                    be_valid_non_zero_summary_statistic)
            if counters.latency:
                expect(
                    counters.latency).to(be_valid_non_zero_summary_statistic)
            if counters.sequence:
                total = (counters.sequence.duplicate + counters.sequence.late +
                         counters.sequence.reordered +
                         counters.sequence.in_order)
                expect(total).to(equal(counters.frame_count))

        if counters.frame_count > 1:
            if counters.interarrival:
                expect(counters.interarrival).to(
                    be_valid_non_zero_summary_statistic)
            if counters.jitter_ipdv:
                expect(counters.jitter_ipdv).to(
                    be_valid_non_zero_summary_statistic)
            if counters.jitter_rfc:
                expect(counters.jitter_rfc).to(
                    be_valid_non_zero_summary_statistic)

            # 0 < timestamp_first <= timestamp_last
            expect(counters.timestamp_last).to(
                be_above(counters.timestamp_first))
            duration = counters.timestamp_last - counters.timestamp_first
            expect(duration).to(be_above_or_equal(datetime.timedelta(0)))

        return True, ['is valid packet analyzer flow counter']
Exemple #3
0
 def _match(self, result):
     expect(result).to(be_a(client.models.PacketAnalyzerFlowDigestResult))
     if result.centroids:
         for i in range(len(result.centroids) - 1):
             left = result.centroids[i]
             right = result.centroids[i + 1]
             expect(int(right.mean)).to(be_above_or_equal(int(left.mean)))
     return True, ['is valid packet analyzer flow digest result']
 def _match(self, config):
     expect(config).to(be_a(client.models.PacketGeneratorConfig))
     if (config.flow_count):
         expect(config.flow_count).to(be_above_or_equal(1))
     expect(config.duration).to(be_valid_traffic_duration)
     expect(config.load).to(be_valid_traffic_load)
     expect(config.traffic).not_to(be_empty)
     for definition in config.traffic:
         expect(definition).to(be_valid_traffic_definition)
     return True, ['is valid packet generator config']
 def _match(self, length):
     expect(length).to(be_a(client.models.TrafficLength))
     has_property = False
     if (length.fixed):
         expect(length.fixed).to(be_above_or_equal(64))
         has_property = True
     if (length.list):
         expect(length.list).not_to(be_empty)
         for l in length.list:
             expect(l).to(be_above_or_equal(64))
         has_property = True
     if (length.sequence):
         expect(length.sequence).to(
             be_a(client.models.TrafficLengthSequence))
         expect(length.sequence.count).to(be_above(0))
         expect(length.sequence.start).to(be_above_or_equal(64))
         has_property = True
     expect(has_property).to(be_true)
     return True, ['is valid traffic length']
Exemple #6
0
    def test_add_recipients_to_existing_message(self, recipients):
        message = Message(
            connection=self.connection,
            collector_id=self.collector_id,
            message_id=self.message_id,
        )

        with HTTMock(self.mock.recipient_add):
            response = message.recipients(recipients)

        expect(response["succeeded"]).to(have_length(be_above_or_equal(1)))
Exemple #7
0
    def test_create_new_message_and_add_a_recipients(self, recipients):
        message = Message(connection=self.connection,
                          collector_id=self.collector_id,
                          config=self.config)

        with HTTMock(MessagesMock(self.config).create):
            message.create()

        with HTTMock(self.mock.recipient_add):
            response = message.recipients(recipients)

        expect(response["succeeded"]).to(have_length(be_above_or_equal(1)))
Exemple #8
0
    def _post_users(self, client, data_trust_id, token_generator):
        '''
        Helper function that creates (and tests creating) a several Users.
        '''
        headers = {
            'content-type': 'application/json',
            'authorization': f'bearer {token_generator.get_token(client)}'
        }
        for user in USERS:
            user['data_trust_id'] = data_trust_id
            response = client.post('/users',
                                   data=json.dumps(user),
                                   headers=headers)
            response_data = response.json
            expect(response.status_code).to(be(201))
        response = client.get('/users', headers=headers)

        expect(len(response.json['response'])).to(be_above_or_equal(3))
Exemple #9
0
    def test_scope_api(self, client, token_generator):
        # Common headers go in this dict
        headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}

        response = client.get('/scopes', headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        print(f'******** {response.json}')
        expect(len(response_data['response'])).to(equal(0))

        # POST some new scoeps
        scope_ids = []
        for scope in SCOPES:
            response = client.post('/scopes', data=json.dumps(scope), headers=headers)
            expect(response.status_code).to(be(201))
            scope_ids.append(response.json['response'][0]['id'])

        # PATCH the first scope
        patched_scope = {
            'scope': SCOPES[0]['scope'].capitalize()
        }
        response = client.patch(f'/scopes/{scope_ids[0]}', data=json.dumps(patched_scope), headers=headers)
        expect(response.status_code).to(be(200))

        # Repost the second scope with PUT
        response = client.put(f'/scopes/{scope_ids[1]}', data=json.dumps(SCOPES[1]), headers=headers)
        expect(response.status_code).to(be(200))

        # Raise a 4xx status code if a scope is duplicated
        response = client.post(f'/scopes/{scope_ids[2]}')
        expect(response.status_code).to(be_above_or_equal(400))

        # Delete all scopes
        for id in scope_ids:
            response = client.delete(f'/scopes/{id}', headers=headers)
            expect(response.status_code).to(be(200))
        response = client.get('/scopes', headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data['response'])).to(equal(0))
Exemple #10
0
def post_users(users, client, token):
    # def post_users(users, client, organization_id, token_generator):
    '''
    Helper function that creates (and tests creating) a collection of Users.
    '''

    headers = {
        'content-type': 'application/json',
        'authorization': f'bearer {token}'
    }
    user_ids = []
    for user in users:
        user['active'] = True
        response = client.post('/users',
                               data=json.dumps(user),
                               headers=headers)
        expect(response.status_code).to(equal(201))
        user_ids.append(response.json['response'][0]['id'])

    expect(len(user_ids)).to(be_above_or_equal(len(users)))

    return user_ids
Exemple #11
0
 def test_ge_is_false_if_other_is_not_empty_fake(self):
     expect(EmptyFake()).not_to(be_above_or_equal(42))
Exemple #12
0
 def test_ge_is_true_if_other_is_empty_fake(self):
     expect(EmptyFake()).to(be_above_or_equal(EmptyFake()))
Exemple #13
0
    def test_data_trust_api(self, client, token_generator):

        # Common headers go in this dict
        headers = {'content-type': 'application/json', 'authorization': f'bearer {token_generator.get_token(client)}'}

        # Database should have pre-populated data trust at the beginning
        response: Response = client.get('/data_trusts', headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data['response'])).to(equal(1))

        # POST a new data trust
        request_body = {
            'data_trust_name': 'BrightHive Test Data Trust'
        }
        response = client.post(
            '/data_trusts', data=json.dumps(request_body), headers=headers)
        expect(response.status_code).to(be(201))
        response_data = response.json
        data_trust_id = response_data['response'][0]['id']

        # GET all
        response: Response = client.get('/data_trusts', headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data['response'])).to(be_above_or_equal(1))

        # Attempt to POST the same data trust
        response = client.post(
            '/data_trusts', data=json.dumps(request_body), headers=headers)
        expect(response.status_code).to(be_above_or_equal(400))

        # GET the data trust by ID
        response = client.get(
            '/data_trusts/{}'.format(data_trust_id), headers=headers)
        expect(response.status_code).to(be(200))

        # Create a new data trust
        request_body['data_trust_name'] = 'BrightHive Test Data Trust 2'
        response = client.post(
            '/data_trusts', data=json.dumps(request_body), headers=headers)
        expect(response.status_code).to(be(201))
        response_data = response.json
        data_trust_id_2 = response_data['response'][0]['id']
        expect(data_trust_id).not_to(equal(data_trust_id_2))

        # Attempt to name both data trusts the same
        response = client.put('/data_trusts/{}'.format(data_trust_id),
                              data=json.dumps(request_body), headers=headers)
        expect(response.status_code).to(be_above_or_equal(400))
        response = client.patch('/data_trusts/{}'.format(data_trust_id),
                                data=json.dumps(request_body), headers=headers)
        expect(response.status_code).to(be_above_or_equal(400))

        # Rename data trust 2 with a PUT
        new_name = str(reversed(request_body['data_trust_name']))
        request_body['data_trust_name'] = new_name
        response = client.put('/data_trusts/{}'.format(data_trust_id_2),
                              data=json.dumps(request_body), headers=headers)
        expect(response.status_code).to(equal(200))

        # Rename data trust 2 with a PATCH
        new_name = str(reversed(request_body['data_trust_name']))
        request_body['data_trust_name'] = new_name
        response = client.patch('/data_trusts/{}'.format(data_trust_id_2),
                                data=json.dumps(request_body), headers=headers)
        expect(response.status_code).to(equal(200))

        # DELETE the data trusts
        response = client.delete(
            '/data_trusts/{}'.format(data_trust_id), headers=headers)
        response = client.delete(
            '/data_trusts/{}'.format(data_trust_id_2), headers=headers)
        expect(response.status_code).to(be(200))
Exemple #14
0
    def test_user_api(self, client, token_generator):
        # Common headers go in this dict
        headers = {
            'content-type': 'application/json',
            'authorization': f'bearer {token_generator.get_token(client)}'
        }

        # Database should be empty at the beginning
        response: Response = client.get('/data_trusts', headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data['response'])).to(be_above_or_equal(1))

        response = client.get('/users', headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data['response'])).to(equal(1))

        # Populate database with a data trust and users
        data_trust_id = self._post_data_trust(client, token_generator)
        self._post_users(client, data_trust_id, token_generator)

        # GET all users
        response = client.get('/users', headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data['response'])).to(be_above_or_equal(3))
        added_users = response_data['response']

        # Attempt to POST an existing user
        response = client.post('/users',
                               data=json.dumps(USERS[0]),
                               headers=headers)
        expect(response.status_code).to(be_above_or_equal(400))

        # Get all users by ID
        for user in added_users:
            response = client.get('/users/{}'.format(user['id']),
                                  headers=headers)
            expect(response.status_code).to(be(200))

        # Rename a user with a PATCH
        user_id = added_users[0]['id']
        new_name = str(reversed(added_users[0]['firstname']))
        single_field_update = {'firstname': new_name}
        response = client.patch('/users/{}'.format(user_id),
                                data=json.dumps(single_field_update),
                                headers=headers)
        expect(response.status_code).to(equal(200))

        # Rename a user with a PUT, expect to fail because not all fields specified
        response = client.put('/users/{}'.format(user_id),
                              data=json.dumps(single_field_update),
                              headers=headers)
        expect(response.status_code).to(equal(422))

        # Rename a user with a PUT, providing the entire object
        added_users[0]['firstname'] = new_name
        added_users[0]['password'] = '******'
        if not added_users[0]['telephone']:
            added_users[0]['telephone'] = 'N/A'
        response = client.put('/users/{}'.format(user_id),
                              data=json.dumps(added_users[0]),
                              headers=headers)
        expect(response.status_code).to(equal(200))

        # DELETE the data trusts and by extension delete the users
        response = client.delete('/data_trusts/{}'.format(data_trust_id),
                                 headers=headers)
        expect(response.status_code).to(equal(200))

        # Ensure users have been deleted by the deletion of the data trust associated with them.
        response = client.get('/users', headers=headers)
        expect(response.status_code).to(be(200))
        response_data = response.json
        expect(len(response_data['response'])).to(equal(1))
Exemple #15
0
        expect((ok, res)).to(be_successful_api_call)
        expect(res).to(have_key("events", be_empty))

    with it("is able to retrieve the last event only"):
        ok, res = self.client.get_events(limit=1)
        expect((ok, res)).to(be_successful_api_call)
        expect(res).to(have_key("events", have_len(1)))

    with it("is able to retrieve the events from the last day"):
        to_s = datetime.now()
        from_s = to_s - timedelta(weeks=2)
        ok, res = self.client.get_events(from_s=from_s, to_s=to_s)

        expect((ok, res)).to(be_successful_api_call)
        expect(res).to(have_key("events", have_len(be_above_or_equal(1))))

    with context("but the from and to parameters are incorrectly specified"):
        with it("returns an error if any of the parameters is specified but not the other"
                ):
            t = datetime.now() - timedelta(weeks=2)
            ok1, res1 = self.client.get_events(from_s=t)
            ok2, res2 = self.client.get_events(to_s=t)

            expect((ok1, res1)).not_to(be_successful_api_call)
            expect((ok2, res2)).not_to(be_successful_api_call)
            expect(res1).to(
                equal("only one of 'from_s' or 'to_s' has been specified, "
                      "both are required when filtering by time"))
            expect(res2).to(
                equal("only one of 'from_s' or 'to_s' has been specified, "
    def test_user_api(self, client, token_generator):
        # Common headers go in this dict
        headers = {
            "content-type": "application/json",
            "authorization": f"bearer {token_generator.get_token(client)}",
        }

        response = client.get("/users", headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data["response"])).to(equal(1))

        # Populate database with users
        post_users(USERS, client, token_generator.get_token(client))

        # GET all users
        response = client.get("/users", headers=headers)
        response_data = response.json
        expect(response.status_code).to(be(200))
        expect(len(response_data["response"])).to(be_above_or_equal(3))
        added_users = response_data["response"]

        # Store ID for all users since we will break the data.
        added_user_ids = []
        for user in added_users:
            added_user_ids.append(user["id"])

        # Attempt to POST an existing user
        response = client.post("/users",
                               data=json.dumps(USERS[0]),
                               headers=headers)
        expect(response.status_code).to(be_above_or_equal(400))

        # Get all users by ID
        for user in added_users:
            response = client.get("/users/{}".format(user["id"]),
                                  headers=headers)
            expect(response.status_code).to(be(200))

        # Update a user with a PATCH
        user_id = added_users[len(added_users) - 1]["id"]
        new_person_id = str(
            reversed(added_users[len(added_users) - 1]["person_id"]))
        single_field_update = {"person_id": new_person_id}
        response = client.patch(
            "/users/{}".format(user_id),
            data=json.dumps(single_field_update),
            headers=headers,
        )
        expect(response.status_code).to(equal(200))

        # Rename a user with a PUT, expect to fail because not all fields specified
        response = client.put(
            "/users/{}".format(user_id),
            data=json.dumps(single_field_update),
            headers=headers,
        )
        expect(response.status_code).to(equal(422))

        # Rename a user with a PUT, providing the entire object
        user_to_update = added_users[len(added_users) - 1]
        user_to_update["password"] = "******"
        user_to_update.pop("role", None)
        user_to_update.pop("date_created", None)
        user_to_update.pop("id", None)
        user_to_update.pop("date_last_updated", None)

        response = client.put(
            "/users/{}".format(user_id),
            data=json.dumps(user_to_update),
            headers=headers,
        )
        expect(response.status_code).to(equal(200))

        # Delete users
        for user_id in added_user_ids:
            response = client.delete(f"/users/{user_id}", headers=headers)
            expect(response.status_code).to(be(200))