def test_configuration_factory(self):
        """Test API configuration factory.

        """

        config = ConfigurationFactory.get_config('TEST')
        expect(config).to(be_a(object))
        expect(config.get_api_name()).to_not(equal('Unknown'))
        expect(config.get_api_version()).to_not(equal('Unknown'))
        expect(config.get_settings()).to(have_key('API_VERSION'))
        expect(config.get_settings()).to(have_key('API_NAME'))
Esempio n. 2
0
 def test_health_endpoint(self, client):
     """Ensure that the API is available and reachable."""
     response: Response = client.get('/health')
     body = response.json
     expect(response.status_code).to(be(200))
     expect(body).to(have_key('api_status'))
     expect(body['api_status']).to(equal('OK'))
Esempio n. 3
0
    def test_client_credentials_flow(self, client):
        """Test Client Credentials OAuth 2.0 flows.

        """
        response = self._get_access_token(client)

        expect(response).to(have_key('access_token'))
        expect(response['token_type']).to(equal('Bearer'))
Esempio n. 4
0
 def it_should_return_an_sid(self):
     expect(self.result).to(have_key('short_url'))
     short_url = self.result['short_url']
     expect(short_url).to(be_a(str))
     expect(self.result).to(equal({
         'success': True,
         'short_url': short_url,
         'url': self.url
     }))
def _healthcheck_response(client, metrics_blob, mocker):
    mocker.patch('brighthive_authlib.providers.BrightHiveProvider.validate_token', return_value=True)
    mocker.patch("json.load", return_value=metrics_blob)

    response = client.get('/health')
    expect(response.status_code).to(be(200))
    expect(response.json).to(have_key('response'))
    
    return response.json['response']
def test_mci_metrics_endpoints(client, metrics_blob, mocker):
    response = _healthcheck_response(client, metrics_blob, mocker)

    expect(response).to(have_key('mci_metrics'))
    endpoints = response['mci_metrics']
    expect(endpoints).to(have_len(2))
    
    ep_names = [ep['endpoint'] for ep in endpoints]
    expected_ep_names = ['users', 'gender']
    expect(ep_names.sort()).to(equal(expected_ep_names.sort()))
Esempio n. 7
0
 def it_should_return_an_sid(self):
     expect(self.result).to(have_key('short_url'))
     short_url = self.result['short_url']
     expect(short_url).to(be_a(str))
     expect(self.result).to(
         equal({
             'success': True,
             'short_url': short_url,
             'url': self.url
         }))
def test_data_resources_endpoints(client, metrics_blob, mocker):
    response = _healthcheck_response(client, metrics_blob, mocker)
    
    expect(response).to(have_key('data_resources_metrics'))
    endpoints = response['data_resources_metrics']
    expect(endpoints).to(have_len(1))
    
    ep_names = [ep['endpoint'] for ep in endpoints]
    expected_ep_names = ['programs']
    expect(expected_ep_names).to(equal(ep_names))
Esempio n. 9
0
    def test_message_sent(self):
        message = Message(
            connection=self.connection,
            collector_id=self.collector_id,
            message_id=self.message_id,
        )

        with HTTMock(self.mock.send):
            response = message.send()

        expect(response).to(have_key("is_scheduled", True))
Esempio n. 10
0
    def test_valid_analyze_url_returned(self):
        with HTTMock(self.mock.by_id):
            survey = self.survey.by_id(survey_id=self.survey_id)

        expect(survey).to(be_a(dict))
        expect(survey).to(have_key('analyze_url'))

        analyze_url = furl(survey["analyze_url"])

        expect(survey["analyze_url"]).to(be_url)
        expect(analyze_url.path.segments[0]).to(equal("analyze"))
Esempio n. 11
0
def validate_field(model, field_name, raises_error=True):
    """
    Raises Validation error for provided field name.

    :param django.db.models.Model model:
    :param String field_name:
    :param raises_error: true - if field validation raises error, false - otherwise
    :return:
    """
    expect_to = getattr(expect(lambda: model.clean_fields()),
                        'to' if raises_error else 'not_to')
    expect_to(raise_error(ValidationError, have_key(field_name)))
Esempio n. 12
0
    def test_invite_created(self):
        config = InviteConfig()
        message = Message(connection=self.connection,
                          collector_id=self.collector_id,
                          config=config)

        with HTTMock(MessagesMock(config).create):
            invite = message.create()

        expect(invite).to_not(be_sent)
        expect(invite).to(be_invite)
        expect(invite).to(have_key("id"))
Esempio n. 13
0
    def test_fetch_latest(self, client):
        """Fetch the latest XKCD comic.

        Args:
            client: Falcon API context injected as a fixture by pytest.

        """

        resp = client.simulate_get('/')
        expect(resp.status).to(be(falcon.HTTP_200))
        for key in VALID_KEYS:
            expect(resp.json).to(have_key(key))
Esempio n. 14
0
 async def test_incr_tripped_count(self, *args):
     with patch('bson.ObjectId') as bson_mock:
         mock_id = 'some-value'
         mock_db = MagicMock()
         mock_db.update_one = CoroutineMock()
         bson_mock.return_value = mock_id
         await CircuitBreaker.incr_tripped_count(mock_id, mock_db)
         mock_db.update_one.assert_awaited()
         bson_mock.assert_called_with(mock_id)
         expect(mock_db.update_one.call_args[0][0]['_id']).to(
             equal(mock_id))
         expect(mock_db.update_one.call_args[0][1]['$inc']).to(
             have_key('tripped_count', 1))
Esempio n. 15
0
    def test_fetch_specific_comic(self, client):
        """Test the ability to fetch a specific XKCD comic by it's identifier.

        Args:
            client: Falcon API context injected as a fixture by pytest.

        """

        resp = client.simulate_get('/1')
        expect(resp.status).to(be(falcon.HTTP_200))
        for key in VALID_KEYS:
            expect(resp.json).to(have_key(key))

        # NOTE(agileronin): At some point in time this test will fail; however it will be an
        # epic day when XKCD releases their 10 millionth comic!
        resp = client.simulate_get('/10000000')
        expect(resp.status).to(be(falcon.HTTP_404))
Esempio n. 16
0
    def test_webhook_create_for_multiple_objects(self, event_type, object_type, method, object_ids):  # noqa:E501
        mock = WebhookMock(
            event_type=event_type,
            object_type=object_type,
            object_ids=object_ids,
            subscription_url="https://example.com"
        )

        with HTTMock(mock.create):
            webhook = Webhook(self.connection)
            response = getattr(webhook, method)(
                event_type=event_type,
                object_ids=object_ids,
                subscription_url="https://example.com"
            )

        expect(response).to(have_key('event_type', event_type))
        expect(response["object_ids"]).to(equal(object_ids))
Esempio n. 17
0
    def test_middleware(self, app, scopes):
        with app.app_context():
            user1 = User(firstname='John', lastname='Doe', age=45)
            user1.ssn = '123456789'
            user1.middlename = 'Evan'
            user1.date_registered = datetime.now()
            db.session.add(user1)
            db.session.commit()

            user2 = User(firstname='Mary', lastname='Doe', age=12)
            user2.ssn = '246771234'
            user2.middlename = 'Jane'
            user2.date_registered = datetime.now()
            db.session.add(user2)
            db.session.commit()

            user3 = User(firstname='Anthony', lastname='Doe', age=20)
            user3.ssn = '21771294'
            user3.middlename = 'Paul'
            user3.date_registered = datetime.now()
            db.session.add(user3)
            db.session.commit()

            test_scope = scopes[len(scopes) - 1]['scope']['ruleset'][0]['rule']
            responses = process_response(test_scope, User)

            # only two records returned since younger than 18 is not allowed
            expect(len(responses)).to(be(2))

            # social security numbers redacted for all users
            for response in responses:
                expect(response).not_to(have_key('id'))
                expect(response['ssn']).to(equal('**********'))
                if response['age'] < 45:
                    expect(response['firstname']).to(equal('**********'))
                    expect(response['lastname']).to(equal('**********'))
                    expect(response['middlename']).to(equal('**********'))
                    expect(response['suffix']).to(equal('**********'))
                if response['age'] == 45:
                    expect(response['date_registered']).to(equal('**********'))
            print(responses)
Esempio n. 18
0
 async def test_create_rule(self, *args):
     with asynctest.patch.object(RateLimiter,
                                 '_set_indexes') as _set_indexes_mock:
         mock_ctx = {
             'path': 'some-path',
             'max_requests': 1,
             'timeout': 1,
             'host': 'some-host',
             'message': 'some-message'
         }
         mock_db = MagicMock()
         mock_service_db = MagicMock()
         mock_sadd = CoroutineMock()
         mock_hmset_dict = CoroutineMock()
         mock_db.sadd = mock_sadd
         mock_db.hmset_dict = mock_hmset_dict
         await RateLimiter.create_rule(mock_ctx, mock_db)
         _set_indexes_mock.assert_called()
         mock_sadd.assert_awaited()
         for key in mock_ctx.keys():
             expect(mock_hmset_dict.await_args[0][1]).to(have_key(key))
             expect(mock_hmset_dict.await_args[0][1][key]).to(
                 equal(mock_ctx[key]))
Esempio n. 19
0
 async def test_create_entry(self, *args):
     with asynctest.patch.object(RateLimiter,
                                 '_set_indexes') as _set_indexes_mock:
         mock_ctx = {
             'rule_id': 'some-id',
             'host': 'some-host',
             'timeout': 1,
         }
         mock_db = MagicMock()
         mock_service_db = MagicMock()
         mock_sadd = CoroutineMock()
         mock_hmset_dict = CoroutineMock()
         mock_expire = CoroutineMock()
         mock_db.sadd = mock_sadd
         mock_db.hmset_dict = mock_hmset_dict
         mock_db.expire = mock_expire
         await RateLimiter.create_entry(mock_ctx, mock_db)
         _set_indexes_mock.assert_called()
         mock_sadd.assert_awaited()
         for key in mock_ctx.keys():
             expect(mock_hmset_dict.await_args[0][1]).to(have_key(key))
             expect(mock_hmset_dict.await_args[0][1][key]).to(
                 equal(mock_ctx[key]))
                'properties': {
                    'dotted.key': 'Do. Or do not. There is no try.',
                    'severity': 4
                }
            }

            self.created = self.client.create_finding(organization,
                                                      source_finding)

        with it('creates the finding'):
            expect(self.created.id).to(equal(self._id))
            expect(self.created.asset_id).to(equal('ASSET_ID_TO_REPLACE'))
            expect(self.created.scanner_id).to(equal(self.source_id))

        with it('uses underscores instead of dots in property keys'):
            expect(self.created.properties).to(have_key('dotted_key'))

        def now(self):
            dt = datetime.utcnow()
            return int((dt - datetime.utcfromtimestamp(0)).total_seconds())

    with it('retrieves id from hostname'):
        project = 'arboreal-logic-197906'
        zone = 'europe-west3-a'
        hostname = 'gke-demo-default-pool-1af4d30b-hnbq'

        instance_id = self.client.get_instance_id_from_hostname(
            project, zone, hostname)

        expect(instance_id).to(equal('6739927742716024409'))
Esempio n. 21
0
 def _match(self, subject):
     expect(subject).to(have_key('Location'))
     return subject['Location'] == self._expected, []
Esempio n. 22
0
 def _match(self, request):
     expect(request).to(have_key('Content-Type'))
     expect(request['Content-Type']).to(equal('application/json'))
     return True, ['is JSON content type']
Esempio n. 23
0
from expects import expect, be, have_key

from pysellus.stock_integrations import slack, integration_classes

with description('the slack integration module'):

    with it('should be in the integration classes dictionary'):
        expect(integration_classes).to(have_key('slack'))
        expect(integration_classes['slack']).to(be(slack.SlackIntegration))

    with it('should initialize with the correct arguments'):
        slack_url = 'an_url'
        slack_channel = 'a_channel'

        slack_instance = slack.SlackIntegration(slack_url)
        another_slack_instance = slack.SlackIntegration(
            slack_url, slack_channel)

        expect(slack_instance._url).to(be(slack_url))
        expect(slack_instance._channel).to(be(None))

        expect(another_slack_instance._url).to(be(slack_url))
        expect(another_slack_instance._channel).to(be(slack_channel))

    with it('should compose a correct on_next message'):
        slack_url = 'an_url'
        slack_element = {'test_name': 'some test'}

        expected_payload = {
            'attachments': [{
                'fallback':
Esempio n. 24
0
from expects import expect, be, have_key

from pysellus.stock_integrations import slack, integration_classes


with description('the slack integration module'):

    with it('should be in the integration classes dictionary'):
        expect(integration_classes).to(have_key('slack'))
        expect(integration_classes['slack']).to(be(slack.SlackIntegration))

    with it('should initialize with the correct arguments'):
        slack_url = 'an_url'
        slack_channel = 'a_channel'

        slack_instance = slack.SlackIntegration(slack_url)
        another_slack_instance = slack.SlackIntegration(slack_url, slack_channel)

        expect(slack_instance._url).to(be(slack_url))
        expect(slack_instance._channel).to(be(None))

        expect(another_slack_instance._url).to(be(slack_url))
        expect(another_slack_instance._channel).to(be(slack_channel))

    with it('should compose a correct on_next message'):
        slack_url = 'an_url'
        slack_element = {
            'test_name': 'some test'
        }

        expected_payload = {
Esempio n. 25
0
import securecscc
from securecscc import origins

from specs.support import fixtures
from specs.support.matchers import be_an_uuid

with description(origins.Falco) as self:
    with before.each:
        self.settings = securecscc.Settings()
        self.mapper = origins.Falco(self.settings)

    with it('uses the source_id assigned to us from Google'):
        finding = self.mapper.create_from(fixtures.event_falco())

        expect(finding).to(have_key('source_id', self.settings.source_id()))

    with it('uses the rule as category'):
        category = 'Terminal shell in container'

        finding = self.mapper.create_from(fixtures.event_falco())

        expect(finding).to(have_key('category', category))

    with it('uses only seconds from event time'):
        event_time = 1526547969

        finding = self.mapper.create_from(fixtures.event_falco())

        expect(finding).to(have_key('event_time', event_time))
        receiver = Receiver(
            consumers=[events_consumer, basket_consumer],
            message_publisher=message_publisher)

        with message_publisher:
            message_publisher.publish(ANY_ARG).delegates(receiver.process)

        total_price = 0
        num_items = 0
        receiver.process(create_basket_created_event(basket_id))
        expect(message_publisher.publish).not_to(have_been_called)

        receiver.process(create_add_item_command(basket_id, SHIRT_ID))
        expect(message_publisher.publish).to(have_been_called_with(
            have_key('kind', ITEM_ADDED)).once)
        total_price += ITEMS[SHIRT_ID]['price']
        num_items += 1

        receiver.process(create_add_item_command(basket_id, SHIRT_ID))
        expect(message_publisher.publish).to(have_been_called_with(
            have_key('kind', ITEM_ADDED)).twice)
        total_price += ITEMS[SHIRT_ID]['price']
        num_items += 1

        receiver.process(create_add_item_command(basket_id, HAT_ID))
        expect(message_publisher.publish).to(have_been_called_with(
            have_key('kind', ITEM_ADDED)).exactly(3))
        total_price += ITEMS[HAT_ID]['price']
        num_items += 1
Esempio n. 27
0
import securecscc


with description(securecscc.SysdigSecureClient) as self:
    with before.all:
        self.client = securecscc.SysdigSecureClient(securecscc.Credentials())

    with context('when retrieving events happened on last minute'):
        with before.all:
            self.events = self.client.events_happened_on_last_minute()

        with it('returns more than 0 events'):
            expect(self.events).to(have_length(be_above(0)))

        with it('event contains an id'):
            expect(self.events[0]).to(have_key('id'))

        with it('event contains the timestamp'):
            expect(self.events[0]).to(have_key('timestamp'))

    with it('retrieves a policy from its id'):
        policy_id = 3120
        policy_name = 'Disallowed SSH Connection'

        policy = self.client.find_policy_by_id(policy_id)

        expect(policy).to(equal(policy_name))

    with context('when finding a hostname from its MAC'):
        with it('returns the hostname'):
            mac = '42:01:0a:9c:00:03'
                                     token=os.getenv("SDC_MONITOR_TOKEN"))
        self.event_name = "event_v2_test_ci"

    with it("is able to create a custom event"):
        call = self.client.post_event(
            name=self.event_name,
            description=
            "This event was created in a CI pipeline for the Python SDK library"
        )
        expect(call).to(be_successful_api_call)

    with it("is able to list the events happened without any filter"):
        time.sleep(3)  # Wait for the event to appear in the feed
        ok, res = self.client.get_events()
        expect((ok, res)).to(be_successful_api_call)
        expect(res).to(have_key("events"))

    with it("is able to list the events created by the tests"):
        time.sleep(3)  # Wait for the event to appear in the feed
        ok, res = self.client.get_events(category=["custom"])
        expect((ok, res)).to(be_successful_api_call)
        expect(res).to(
            have_key("events", contain(have_keys(name=self.event_name))))

    with it("fails to retrieve the events with an incorrect category"):
        ok, res = self.client.get_events(category=['incorrect_category'])

        expect(ok).to(be_false)
        expect(res).to(equal("Invalid category 'incorrect_category'"))

    with it("is able to retrieve events that match a status"):
Esempio n. 29
0
        node_name = self.kubernetes_client.find_node_running_pod('nginx')

        node = self.kubernetes_client.taint_node(node_name, 'playbooks',
                                                 'true', 'NoSchedule')

        expect(node.spec.taints[0].effect).to(equal('NoSchedule'))
        expect(node.spec.taints[0].key).to(equal('playbooks'))
        expect(node.spec.taints[0].value).to(equal('true'))

    with it('adds label to a pod'):
        self._create_nginx_pod()

        pod = self.kubernetes_client.add_label_to_pod('nginx', 'testing',
                                                      'true')

        expect(pod.metadata.labels).to(have_key('testing', 'true'))

    with it('starts sysdig capture for'):
        self._create_nginx_pod()

        job = self.kubernetes_client.start_sysdig_capture_for(
            's3', 'nginx', int(time.time()), 10, 'any s3 bucket',
            'any aws key id', 'any aws secret key')

        expect(job).not_to(be_none)

    def _create_nginx_pod(self):
        current_directory = os.path.dirname(os.path.realpath(__file__))
        pod_manifesto = os.path.join(current_directory, '..', 'support',
                                     'deployment.yaml')
Esempio n. 30
0
from mamba import description, it, before
from expects import expect, be_above, have_key
from patchscheme.scheme import Scheme
import patchscheme.strategies as st
from datetime import datetime


class PatchPerson(Scheme):
    created_at = st.Suppress()
    updated_at = st.Force(datetime.now)


with description(PatchPerson) as self:

    with before.each:
        self.stored = dict(
            created_at=datetime(2019, 9, 27, 0, 0),
            updated_at=datetime(2019, 9, 27, 0, 0)
        )
        self.payload = {}
        self.payload.update(self.stored)

    with it('should patch using Force and Suppress'):
        now = datetime.now()
        patch = PatchPerson(self.stored, self.payload).map()
        expect(patch).not_to(have_key('created_at'))
        expect(patch).to(have_key('updated_at'))
        expect(patch['updated_at']).to(be_above(now))
Esempio n. 31
0
        book_without_author = Book(
            book_id=str(uuid.uuid4()),
            name='',
            rating=0.2,
        )
        with app.app_context():
            db.session.add(book_without_author)
            db.session.commit()
            retrieved_book = Book.query.\
                filter_by(book_id=book_without_author.book_id).\
                first()
        result = model_to_dict(
            sqlalchemy_model=retrieved_book,
            paths=['author'],
        )
        expect(result).to(have_key('author'))
        expect(result['author']).to(equal(None))

    with it('converts a deeply nested relationship'):
        with app.app_context():
            db.session.add(genre_model)
            db.session.add(book_genre_model)
            db.session.commit()
            retrieved_genre = Book.query. \
                filter_by(id=1). \
                options(joinedload('genre')). \
                first()
            result = model_to_dict(
                sqlalchemy_model=retrieved_genre,
                paths=['genre'],
            )
Esempio n. 32
0
from mamba import description, context, it
from expects import expect, be_true, have_key, equal

import nameday

TODAY_SPAIN_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country=es'
SPAIN_NAMES_KEY = 'name_es'

with context('http client specs'):
    with before.each:
        self.http_client = nameday.HttpClient()

    with context('getting today\'s namedays for Spain'):
        with it('returns a valid response'):
            response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL)

            expect(response.ok).to(be_true)

        with it('returns namedays for Spain'):
            response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL)

            expect(response.json().get('data')).to(have_key(SPAIN_NAMES_KEY))

        with it('returns current day and month'):
            response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL)

            now = datetime.now()
            expect(response.json().get('data').get('day')).to(equal(now.day))
            expect(response.json().get('data').get('month')).to(
                equal(now.month))