Beispiel #1
0
from mamba import describe, it, context
from unittest.mock import MagicMock

from test_utils.anki import mock_anki_modules

mock_anki_modules()

from crowd_anki.export.anki_exporter_wrapper import AnkiJsonExporterWrapper

DUMMY_EXPORT_DIRECTORY = "/tmp"

TEST_DECK_ID = 1

with describe(AnkiJsonExporterWrapper) as self:
    with context("user is trying to export dynamic deck"):
        with it("should warn and exit without initiating export"):
            exporter_mock = MagicMock()
            notifier_mock = MagicMock()

            collection_mock = MagicMock()
            collection_mock.decks.get.return_value = {'dyn': True}

            subject = AnkiJsonExporterWrapper(collection_mock, TEST_DECK_ID, exporter_mock, notifier_mock)

            subject.exportInto(DUMMY_EXPORT_DIRECTORY)

            notifier_mock.warning.assert_called_once()
            exporter_mock.export_to_directory.assert_not_called()
Beispiel #2
0

CONFIG = Config(os.path.join(os.path.dirname(__file__), os.environ.get('MAMBA_CONFIG', 'config.yaml')))


with description('Ports,', 'ports') as self:
    with description('REST API,'):

        with before.all:
            service = Service(CONFIG.service())
            self.process = service.start()
            self.api = client.api.PortsApi(service.client())

        with description('list,'):
            with description('unfiltered,'):
                with it('returns valid ports'):
                    ports = self.api.list_ports()
                    expect(ports).not_to(be_empty)
                    for port in ports:
                        expect(port).to(be_valid_port)

            with description('filtered,'):
                with description('known existing kind,'):
                    with it('returns valid ports of that kind'):
                        ports = self.api.list_ports(kind='dpdk')
                        expect(ports).not_to(be_empty)
                        for port in ports:
                            expect(port).to(be_valid_port)
                            expect(port.kind).to(equal('dpdk'))

                with description('known non-existent kind,'):
Beispiel #3
0
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

from mamba import description, context, it
from expects import expect, equal

import json

test_doc_path = './data/test_doc.json'

try:
    with description('ThriftKV') as self:
        doc_id = ''
        with it('the create method is called and returns a mongo object id'):
            transport = TSocket.TSocket('0.0.0.0', 9090)
            transport = TTransport.TBufferedTransport(transport)
            protocol = TBinaryProtocol.TBinaryProtocol(transport)
            client = ThriftKVService.Client(protocol)
            transport.open()

            # Get thrift client and open transport protocol
            with open(test_doc_path) as f:
                global doc_id
                doc = f.read()
                doc_id = json.loads(client.create(doc))

                expect('$oid' in doc_id.keys())

            transport.close()
Beispiel #4
0
from mamba import description, context, it, before, after
from expects import equal, expect, be_a, be, have_len, be_true, contain
from places import Square
from board import Board
from pieces import *
from move import Move
from game import Game

with description('board') as self:

    with it('allows en passant as an option'):
        b = Board()

        m1 = b._make_move('a1a4')
        b.move(m1)

        m2 = b._make_move('b6b4')
        b.move(m2)

        expect(b.grid['a'][4].piece.available_moves(b)).to(
            contain(b.grid['b'][5]))

    with it('allows en passant only if the pawn move was last turn'):
        b = Board()

        m1 = b._make_move('a1a4')
        b.move(m1)

        m2 = b._make_move('b6b4')
        b.move(m2)
Beispiel #5
0
from mamba import description, it
from expects import expect, have_length, be_above

import os

import infrastructure

with description(infrastructure.AnchoreClient) as self:
    with it('retrieves images with stop policy results'):
        user = os.environ['ANCHORE_CLI_USER']
        password = os.environ['ANCHORE_CLI_PASS']
        url = os.environ['ANCHORE_CLI_URL']

        client = infrastructure.AnchoreClient(user, password, url, True)

        result = client.get_images_with_policy_result('stop')

        expect(result).to(have_length(be_above(1)))
Beispiel #6
0
from mamba import description, it

with description('Fixture#without_inner_contexts'):
    with it('first example'):
        pass

    with it('second example'):
        pass

    with it('third example'):
        pass
from mamba import shared_context, it

with shared_context('Shared Context'):
    with it('example'):
        pass
Beispiel #8
0
from mamba import description, context, it
from expects import expect, contain

with description('checking if string contains a character'):
    with context('given a character and a string'):
        with context('when the string contains the character'):
            with it('returns true'):
                character = 'C'
                string = 'PyConES2018'

                expect(string).to(contain(character))

        with context('when the string does NOT contain the character'):
            with it('return false'):
                character = 'x'
                string = 'PyConES2018'

                expect(string).not_to(contain(character))


from mamba import description, context, it
try:
    from unittest.mock import patch
except ImportError:
    from mock import patch

from expects import expect, be


class ExampleClass(object):

    def hello(self):
        return 'Hello'


with description('Testing with unittest.mock'):

    with context('when class method is mocked'):
        with it('returns mocked value'):
            with patch.object(ExampleClass, 'hello', return_value='World!') as mock_method:
                expect(mock_method()).to(be('World!'))
from mamba import describe, it, context
from unittest.mock import MagicMock

from crowd_anki.export.anki_exporter_wrapper import AnkiJsonExporterWrapper

DUMMY_EXPORT_DIRECTORY = "/tmp"

TEST_DECK_ID = 1

with describe(AnkiJsonExporterWrapper) as self:
    with context("user is trying to export dynamic deck"):
        with it("should warn and exit without initiating export"):
            exporter_mock = MagicMock()
            notifier_mock = MagicMock()

            collection_mock = MagicMock()
            collection_mock.decks.get.return_value = {'dyn': True}

            subject = AnkiJsonExporterWrapper(collection_mock, TEST_DECK_ID, exporter_mock, notifier_mock)

            subject.exportInto(DUMMY_EXPORT_DIRECTORY)

            notifier_mock.warning.assert_called_once()
            exporter_mock.export_to_directory.assert_not_called()
PENDING_DECORATOR_AS_ROOT_PATH = spec_abspath('with_pending_decorator_as_root.py')
WITH_RELATIVE_IMPORT_PATH = spec_abspath('with_relative_import.py')
WITH_TAGS_PATH = spec_abspath('with_tags.py')
WITH_FOCUS_PATH = spec_abspath('with_focus.py')
SHARED_CONTEXT_PATH = spec_abspath('with_shared_context.py')
INCLUDED_CONTEXT_PATH = spec_abspath('with_included_context.py')


def _load_module(path):
    example_collector = ExampleCollector([path])
    return list(example_collector.modules())[0]


with description(ExampleCollector):
    with context('when loading from file'):
        with it('loads module from absolute path'):
            module = _load_module(IRRELEVANT_PATH)

            expect(inspect.ismodule(module)).to(be_true)

        with it('loads module from relative path'):
            module = _load_module(spec_relpath('without_inner_contexts.py'))

            expect(inspect.ismodule(module)).to(be_true)

    #FIXME: Mixed responsabilities in test [collect, load]??
    with context('when loading'):
        with it('orders examples by line number'):
            module = _load_module(spec_abspath('without_inner_contexts.py'))

            examples = loader.Loader().load_examples_from(module)
Beispiel #12
0
from mamba import description, it
from unittest.mock import MagicMock

from test_utils.anki import mock_anki_modules

mock_anki_modules()

from crowd_anki.anki.hook_vendor import HookVendor
from crowd_anki.utils.config import AUTOMATED_SNAPSHOT

with description(HookVendor):
    with it('should only setup snapshot hooks if plugin config says so'):
        hook_manager = MagicMock()
        vendor = HookVendor(MagicMock(), hook_manager)
        vendor.config = {AUTOMATED_SNAPSHOT: False}

        vendor.setup_snapshot_hooks()

        hook_manager.hook.assert_not_called()
Beispiel #13
0

def staged_files(repository):
    staged = porcelain.status(repository.dulwich_repo).staged
    return staged['modify'] + staged['add']


def mock_git_interface(add=tuple()):
    git = MagicMock()
    git.status.return_value = GitStatus(dict(add=add, modify=[], delete=[]), [], [])
    return git


with description(DulwichAnkiRepo) as self:
    with context('init'):
        with it("should use existing repo if it's present"):
            with TemporaryDirectory() as dir_name:
                repo_path = Path(dir_name)
                dulwich_repo = porcelain.init(repo_path)

                assert_repo_exists_at_given_path_after_init(repo_path)

        with it('should create a new repo if it does not exist'):
            with TemporaryDirectory() as dir_name:
                repo_path = Path(dir_name)

                assert_repo_exists_at_given_path_after_init(repo_path)

    with context('add_all'):
        with it("should add new files"):
            with TemporaryDirectory() as dir_name:
Beispiel #14
0
                self.chassis = '172.18.0.2'
                self.slot = 1
                self.port = 1
                #print(os.environ)
                if os.environ.has_key('CSP1'):
                    (self.chassis, self.slot,
                     self.port) = extract_chassis(os.environ['CSP1'])

                # conn and msg_set is a must for calling send_message
                self.conn = connect_chassis(self.chassis)
                self.msg_set_name = 'admin_1'
                self.reservedports = False
            with after.all:  # Don't use multiple before.all/after.all(or .each) in different contexts, see https://github.com/nestorsalceda/mamba/issues/130 for details
                pass  # The last test case  has released the port

            with it('gets port group type'):
                msg_name = 'admin_1.GetPortGroupType'
                msg_content = {
                    "portGroup": [{
                        "slot": -1,
                        "portGroup": -1,
                        "port": -1
                    }]
                }
                resp_dict = send_msg(self, self.conn, msg_name, msg_content)
                portTypeList = resp_dict['pgTypeList']
                expect(portTypeList[0]['pgType']).to(equal('VM-1G-V1-1P'))

            with it('gets the port status'):
                msg_name = 'admin_1.GetPortGroupPortStatus'
                msg_content = {
from mamba import shared_context, included_context, describe, it

SHARED_CONTEXT = 'Shared Context'

with shared_context(SHARED_CONTEXT):
    with it('shared example'):
        pass


with describe('Real tests'):
    with included_context(SHARED_CONTEXT):
        with it('added example'):
            pass
from mamba import description, context, it
from expects import expect, equal


def fibonacci(index):
    pass


with description('fibonacci specs'):
    with context('for index 0'):
        with it('has value 0'):
            index = 0

            value = fibonacci(index)

            expect(value).to(equal(0))
Beispiel #17
0
from mamba import description, it, before, context
from expects import expect, be_none, raise_error

import os

from playbooks import infrastructure

with description(infrastructure.PhantomClient) as self:
    with before.each:
        self.phantom_client = infrastructure.PhantomClient(
            os.environ['PHANTOM_USER'],
            os.environ['PHANTOM_PASSWORD'],
            os.environ['PHANTOM_BASE_URL'],
            verify_ssl=False)

    with it('creates a container in Phantom Server'):
        container = {
            'name': 'My Container',
            'description': 'Useful description of this container.',
            'label': 'events',
            'run_automation': False,
            'severity': 'high',
            'status': 'new',
            'start_time': '2015-03-21T19:28:13.759Z',
        }

        container = self.phantom_client.create_container(container)

        expect(container['id']).not_to(be_none)

    with context('when an error happens'):
Beispiel #18
0
        "sentiment":
        "Positive",
        "tickers": ["AAPL"],
        "summary":
        "sample summary",
        "timestamp":
        "1579141155"
    }],
    "timestamp":
    1579125281,
    "size":
    4
}]

with description('Graphelier News:') as self:
    with it('should make sure the root url is exposed'):
        root_response = TESTING_CLIENT.get('/')
        response_data = root_response.get_json()
        expect(root_response.status_code).should.equal(200)
        response_data['message'].should.equal('Graphelier News')

    with it('should make sure the news clusters url is exposed'):
        with patch('server.views.fetch_n_clusters_from_time') as mock_fetch:
            mock_fetch.return_value = []
            nc_response = TESTING_CLIENT.get('/news_clusters/123')

    with it('should return a 400 on a non-int timestamp'):
        with patch('server.views.fetch_n_clusters_from_time') as mock_fetch:
            mock_fetch.return_value = []
            nc_response = TESTING_CLIENT.get('/news_clusters/12asdf3')
            response_data = nc_response.get_json()
Beispiel #19
0
from mamba import description, context, it
from expects import expect, equal

import tennis

with description('Tennis') as self:
    with it('starts with 0 - 0 score'):
        rafa_nadal = "Rafa Nadal"
        roger_federer = "Roger Federer"
        game = tennis.Game(rafa_nadal, roger_federer)

        expect(game.score()).to(equal((0, 0)))
from expects import expect, be
from mamba import description, it
from unittest.mock import MagicMock

from crowd_anki.representation import deck_initializer

DYNAMIC_DECK = {'dyn': True}

TEST_DECK = "test deck"

with description("Initializer from deck") as self:
    with it("should return None when trying to export dynamic deck"):
        collection = MagicMock()

        collection.decks.byName.return_value = DYNAMIC_DECK

        expect(deck_initializer.from_collection(collection, TEST_DECK)).to(be(None))
Beispiel #21
0
from mamba import description, it
from expects import expect, be_none

from amadeus import version

with description('Amadeus') as self:
    with it('should have a version'):
        expect(version).not_to(be_none)
Beispiel #22
0
from mamba import description, context, it

with description('Refactoring Goodies') as self:
    with it('allows calling a defined method inside the example group'):
        assert self.hello('python') != self.hello('pandas')

    def hello(self, world):
        return 'hello, %s'.format(world)
WITH_RELATIVE_IMPORT_PATH = spec_abspath('with_relative_import.py')
WITH_TAGS_PATH = spec_abspath('with_tags.py')
WITH_FOCUS_PATH = spec_abspath('with_focus.py')
SHARED_CONTEXT_PATH = spec_abspath('with_shared_context.py')
INCLUDED_CONTEXT_PATH = spec_abspath('with_included_context.py')
HELPER_METHODS_PATH = spec_abspath('with_helper_methods.py')


def _load_module(path):
    example_collector = ExampleCollector([path])
    return list(example_collector.modules())[0]


with description(ExampleCollector):
    with context('when loading from file'):
        with it('loads module from absolute path'):
            module = _load_module(IRRELEVANT_PATH)

            expect(inspect.ismodule(module)).to(be_true)

        with it('loads module from relative path'):
            module = _load_module(spec_relpath('without_inner_contexts.py'))

            expect(inspect.ismodule(module)).to(be_true)

    #FIXME: Mixed responsabilities in test [collect, load]??
    with context('when loading'):
        with it('orders examples by line number'):
            module = _load_module(spec_abspath('without_inner_contexts.py'))

            examples = loader.Loader().load_examples_from(module)
from mamba import description, it, _it
from pathlib import Path
from unittest.mock import MagicMock

from crowd_anki.anki.adapters.anki_deck import AnkiDeck
from crowd_anki.history.anki_deck_archiver import AnkiDeckArchiver

with description(AnkiDeckArchiver) as self:
    with it("inits repo, archives the deck there and commits"):
        base_path = Path('dummy_dir')
        deck_path = base_path.joinpath('deck_name')

        deck_exporter_mock = MagicMock()
        deck_exporter_mock.export_to_directory.return_value = deck_path

        repo_mock = MagicMock()
        deck = AnkiDeck({})
        archival_reason = "whee"

        AnkiDeckArchiver(deck, base_path, deck_exporter_mock, lambda _: repo_mock).archive(reason=archival_reason)

        deck_exporter_mock.export_to_directory.assert_called_once_with(deck, base_path)
        repo_mock.stage_all.assert_called_once()
        repo_mock.commit.assert_called_once_with(archival_reason)

    with _it("should delete all existing content of the repo before adding new one"):
        ''' 
        Not sure if this is a good idea, this will help with cleaning out the media files not used anymore 
        but may adversely affect the user if they are to add custom things to the repo. 
        I can consider making this configurable per repo.
        '''
Beispiel #25
0
from mamba import description, context, it
from expects import *
from services.list_attendees import ListAttendees

with description('ListAttendees') as self:
    with it('returns a list'):
        expected = [{'name': 'Foo'}, {'name': 'Bar'}]
        expect(expected == ListAttendees().list.run().value.result).to(be_true)
Beispiel #26
0
from mamba import description, context, it
from expects import expect, equal

import file_extractor
import regex_project_type

with description('File Extractor'):
    with context('for a python project'):
        with context('given a list of files'):
            with it('gets the python files'):
                python_regex = regex_project_type.RegexProjectGenerator(
                    ['python']).regex()[0]
                test_file_list = ['foo.py', 'foo.txt']
                _file_extractor = file_extractor.FileExtractorFromRegex(
                    python_regex)

                result = _file_extractor.process(test_file_list)

                expect(result).to(equal(['foo.py']))
# https://github.com/nestorsalceda/mamba
from mamba import description, context, it
from expects import expect, equal

from create_stan_lang import *

with description("parse_args") as self:
    with it("parses empty argument correctly"):
        expect(parse_args("")).to(equal([]))
    #
    with it("parses ~ argument correctly regardless of spaces"):
        expect(parse_args("~")).to(equal(None))
        expect(parse_args("~ ")).to(equal(None))
        expect(parse_args("~  ")).to(equal(None))
        expect(parse_args(" ~")).to(equal(None))
        expect(parse_args("  ~")).to(equal(None))
        expect(parse_args(" ~ ")).to(equal(None))
    #
    with it("parses single argument into a single element list"):
        expect(parse_args("T x")).to(equal([{'type': 'T', 'name': 'x'}]))
        expect(parse_args("reals theta")).to(equal([{'type': 'reals', 'name': 'theta'}]))
    #
    with it("parses multiple arguments into a multi-element list"):
        expect(parse_args("T x, T y")
        ).to(equal([{'type': 'T', 'name': 'x'},
                    {'type': 'T', 'name': 'y'}]))
        expect(parse_args("matrix x, matrix y")
        ).to(equal([{'type': 'matrix', 'name': 'x'},
                    {'type': 'matrix', 'name': 'y'}]))
Beispiel #28
0
from common import Config, Service
from common.matcher import be_valid_module, raise_api_exception

CONFIG = Config(
    os.path.join(os.path.dirname(__file__),
                 os.environ.get('MAMBA_CONFIG', 'config.yaml')))

with description('Modules, ', 'modules') as self:
    with before.all:
        service = Service(CONFIG.service())
        self.process = service.start()
        self.api = client.api.ModulesApi(service.client())

    with description('list, '):
        with description('all, '):
            with it('returns list of modules'):
                modules = self.api.list_modules()
                expect(modules).not_to(be_empty)
                for module in modules:
                    expect(module).to(be_valid_module)

            with description('unsupported method, '):
                with it('returns 405'):
                    expect(lambda: self.api.api_client.call_api(
                        '/modules', 'PUT')).to(
                            raise_api_exception(405, headers={'Allow': "GET"}))

    with description('get, '):
        with description('known module, '):
            with description('packetio'):
                with it('succeeds'):
Beispiel #29
0
from mamba import description, it

with description('Fixture#with_tags', 'integration'):
    with it('first example', 'unit'):
        pass
Beispiel #30
0
review_dict = {
    'id': REVIEW_UUID,
    'text': 'scathing review - pigs cant talk'
}

with app.app_context():
    db.drop_all()
    db.create_all()
    db.session.add(author_model)
    db.session.add(book_model)
    db.session.add(review_model)
    db.session.commit()

with description('model_to_dict') as self:
    with it('converts a flat model into a dict'):
        with app.app_context():
            retrieved_book = Book.query.filter_by(book_id=BOOK_UUID).first()
        result = model_to_dict(
            sqlalchemy_model=retrieved_book,
        )
        expect(result).to(have_keys(**book_dict))

    with it('converts a singly-nested relationship'):
        with app.app_context():
            retrieved_book = Book.query.\
                filter_by(book_id=BOOK_UUID).\
                options(joinedload('author')).\
                first()
            result = model_to_dict(
                sqlalchemy_model=retrieved_book,
def snmp_integer(value):
    return types.PySnmpValue(types.PySnmpTypes().integer(value))


def snmp_octect_string(value):
    return types.PySnmpValue(types.PySnmpTypes().octect_string(value))


with description('SNMP Client') as self:
    with before.each:
        self.snmp_client = clients.PySnmpClient()

    with context('FEATURE: snmpget'):
        with context('happy path'):
            with it('returns the values'):
                oid1 = '1.3.6.1.4.1.4998.1.1.10.1.4.2.1.29.1.10'
                oid2 = '1.3.6.1.4.1.4998.1.1.10.1.4.2.1.29.1.11'

                result = self.snmp_client.get(SNMP_HOST,
                                              READ_ONLY_COMMUNITY,
                                              [oid1, oid2],
                                              port=SNMP_PORT)

                expect(result).to(
                    equal([(oid1, snmp_integer(999)),
                           (oid2, snmp_integer(31))]))

        with context('having an invalid community'):
            with it('raises an exception after a timeout'):
                oid = '1.1'
from mamba import description, it, context
from expects import expect, equal


RETURN_VALUE = '42'

with description('Refactoring goodies') as self:

    def a_method(self, return_value=RETURN_VALUE):
        return return_value

    with it('uses methods defined inside its context'):
        expect(self.a_method()).to(equal(RETURN_VALUE))

    with context('when using nested contexts'):

        with it('uses methods defined inside its parent'):
            expect(self.a_method()).to(equal(RETURN_VALUE))

    with describe('Execution context of methods'):
        with context('When the value is defined in a before all hook of the same context'):

            def method_with_context(self):
                return self.context_value

            with before.all:
                self.context_value = RETURN_VALUE

            with it('returns the value defined in the before all hook'):
                expect(self.method_with_context()).to(equal(RETURN_VALUE))
Beispiel #33
0
from mamba import description, it
from expects import expect, equal, be_an, be_none
from problems.string.roman import roman_to_arabic, arabic_to_roman, is_roman

with description('roman_to_arabic') as self:
    with it('should return the Arabic representation of a Roman numeral'
            ) as self:
        expect(roman_to_arabic('MDCCCLXVI')).to(equal(1866))
        expect(roman_to_arabic('XIV')).to(equal(14))
        expect(roman_to_arabic('LXXXIX')).to(equal(89))
        expect(roman_to_arabic('XCI')).to(equal(91))
        expect(roman_to_arabic('DCCCXC')).to(equal(890))
        expect(roman_to_arabic('MCMLXXXIX')).to(equal(1989))
with description('arabic_to_roman') as self:
    with it('should return the Roman representation of an Arabic numeral'
            ) as self:
        expect(arabic_to_roman(1666)).to(equal('MDCLXVI'))
        expect(arabic_to_roman(91)).to(equal('XCI'))
with description('is_roman') as self:
    with it('should not accept more than three consecutive numerals') as self:
        expect(is_roman('XXXX')).to(be_none)
    with it('should reject any sequential repetition of V, L, or D') as self:
        expect(is_roman('LL')).to(be_none)
        expect(is_roman('DDC')).to(be_none)
        expect(is_roman('XVV')).to(be_none)
    with it('should allow valid exceptions of order') as self:
        expect(is_roman('IV')).to(be_an(object))
        expect(is_roman('IX')).to(be_an(object))
        expect(is_roman('XC')).to(be_an(object))
        expect(is_roman('XL')).to(be_an(object))
        expect(is_roman('CD')).to(be_an(object))
Beispiel #34
0
from mamba import description, context, it
from expects import expect, equal
import json
from blsqpy.descriptor import Descriptor


def json_fixture_content(filename):
    print("reading", filename)
    with open(filename+".json", encoding='utf-8') as f:
        return json.loads(f.read())


with description('Parsing json config') as self:
    with it('loads them as namedTupples'):
        config = Descriptor.load("./specs/fixtures/config/demo")
        expect(config.demo.test.hello).to(equal("world"))

    with it('loads them as namedTupples and normalize states'):
        config = Descriptor.load("./specs/fixtures/config/parametrized-raw")
        jsonDescriptor = Descriptor.to_json(config)
        print(jsonDescriptor)
        expect(json.loads(jsonDescriptor)).to(
            equal(
                json_fixture_content(
                    "./specs/fixtures/config/parametrized-final"))
        )
Beispiel #35
0
import pandas as pd
from mamba import description, context, it, before
from expects import expect, equal

from blsqpy.levels import Levels

with description('levels') as self:
    with it('to_level_uid'):
        path = "/vJRQh3jzmwU/lZTyT0gbMS6/C2qfrNWcbjx/nxIbiSpPubg"
        expect(
            [
                Levels.to_level_uid(path, 1),
                Levels.to_level_uid(path, 2),
                Levels.to_level_uid(path, 3),
                Levels.to_level_uid(path, 4),
                Levels.to_level_uid(path, 5),
                Levels.to_level_uid(path, 6),
            ]
        ).to(equal([
            'vJRQh3jzmwU',
            'lZTyT0gbMS6',
            'C2qfrNWcbjx',
            'nxIbiSpPubg',
            None,
            None]
        ))

    with it('max_level'):

        def expect_level(paths, expected_level):
            df = pd.DataFrame(data=paths,
Beispiel #36
0
import requests
import time
import configuration
from mamba import description, context, it
from expects import expect, be_true, have_length, equal, be_a, have_property, be_none

headers = {'content-type': 'application/json', 'accept': 'application/json'}
with description('Zipkin tracing functionality'):
    with before.all:
        #Read Config file
        configuration.setenv(self)

    with context('Deploy Zipkin and make sure port forwarded to localhost'):
        with it('Bookinfo Zipkin tracing feature'):
            for _ in range(10):
                r = requests.get(self.url)
                r.status_code
                expect(r.status_code).to(equal(200))
            r1 = requests.get(self.zipkin)
            r1.status_code
            expect(r1.status_code).to(equal(200))
            if 'productpage' in r1.text:
                expect(0).to(equal(0))
            else:
                expect(0).not_to(equal(0))
            configuration.generate_request(self)
with description("Policies v1") as self:
    with before.all:
        self.clientV1 = SdSecureClientV1(sdc_url=os.getenv(
            "SDC_SECURE_URL", "https://secure.sysdig.com"),
                                         token=os.getenv("SDC_SECURE_TOKEN"))
    with after.each:
        self.cleanup_policies()

    def cleanup_policies(self):
        _, res = self.clientV1.list_policies()
        for policy in res['policies']:
            if str(policy["name"]).startswith("Test - "):
                ok, res = self.clientV1.delete_policy_id(policy["id"])
                expect((ok, res)).to(be_successful_api_call)

    with it("is able to list all existing policies"):
        ok, res = self.clientV1.list_policies()
        expect((ok, res)).to(be_successful_api_call)

    with it("is able to list all policies priorities"):
        ok, res = self.clientV1.get_policy_priorities()
        expect((ok, res)).to(be_successful_api_call)

    with it("is able to change the evaluation order of policies"):
        ok, res = self.clientV1.get_policy_priorities()
        random.shuffle(res['priorities']['policyIds'])
        ok, res = self.clientV1.set_policy_priorities(json.dumps(res))
        expect((ok, res)).to(be_successful_api_call)

    with it("is able to add a policy from JSON"):
        call = self.clientV1.add_policy(policy_json())
Beispiel #38
0
from mamba import description, context, it
from expects import expect, equal

with description('Addition') as self:
  with it('adds two numbers'):
    expect(1 + 1).to(equal(2))
from unittest.mock import MagicMock

from expects import expect, contain
from mamba import describe, it, context

from test_utils.anki import mock_anki_modules

mock_anki_modules()
from aqt import mw

from crowd_anki.config.config_settings import ConfigSettings, NoteSortingMethods

with describe(ConfigSettings) as self:
    with context("someone interacts with any config setting"):
        with it("do not sort / sort by none"):
            config = ConfigSettings(mw.addonManager, {
                "automated_snapshot": True
            })

            assert config.automated_snapshot

        with it("get all the NoteSortingMethod values"):
            valid_sorting_methods = list(NoteSortingMethods.values())
            assert len(valid_sorting_methods) > 0
            assert isinstance(valid_sorting_methods, list)

        with it("tries to find the invalid config entries"):
            config = ConfigSettings(mw.addonManager)

            valid_sorting_methods = list(NoteSortingMethods.values())
Beispiel #40
0
from multiprocessing import Queue
from queue import PriorityQueue
import array
import heapq


class Car:
    def __init__(self, color, mileage, automatic):
        self.color = color
        self.mileage = mileage
        self.automatic = automatic


with description('Chapter05') as self:
    with context('dicts'):
        with it('fast lookup'):
            phonebook: Dict[str, int] = {
                'bob': 7387,
                'alice': 3719,
                'jack': 7052,
                }
            assert phonebook['alice'] == 3719

            squares = {x: x * x for x in range(6)}
            assert len(squares.keys()) == 6

    with context('ordered dict'):
        with it('keeps keys in order'):
            d = OrderedDict(one=1, two=2, three=3)
            assert d['two'] == 2
            d['four'] = 4
from mamba import _description, it, context

with _description('Fixture#with_pending_decorator_as_root'):

    with it('pending spec'):
        pass

    with context('when pending context'):
        with it('pending spec inside context'):
            pass