示例#1
0
# Test ceases for messageset admin_1
import os
from mamba import description, context, it
from expects import expect, equal

from common.CommonUtils import *
# CSPLIST is defined in hw_disc.txt in JSON format, you can define any alias for the port, CSP1 and CSP2 is used for a B2B setup

with description('Admin:', 'admin') as self:
    with context('when a chassis is given,'):
        with context('and connects to the chassis,'):
            with before.all:  # Don't use multiple before.all/after.all(or .each) in different contexts, see https://github.com/nestorsalceda/mamba/issues/130 for details
                # using the first chassis/slot/port
                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 = {
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))
示例#3
0
from expects.matchers import Matcher
from common import Config, Service
from common.helper import (make_dynamic_results_config, check_modules_exists,
                           get_block_dynamic_results_fields,
                           block_generator_model, file_model, bulk_start_model,
                           bulk_stop_model, wait_for_file_initialization_done)
from common.matcher import (be_valid_block_device, be_valid_block_file,
                            be_valid_block_generator,
                            be_valid_block_generator_result, has_location,
                            raise_api_exception, be_valid_dynamic_results)

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

with description('Block,', 'block') as self:
    with description('REST API,'):
        with before.all:
            service = Service(CONFIG.service())
            self.process = service.start()
            self.api = client.api.BlockGeneratorApi(service.client())
            if not check_modules_exists(service.client(), 'block'):
                self.skip()

        with description('invalid HTTP methods,'):
            with description('/block-devices,'):
                with it('returns 405'):
                    expect(lambda: self.api.api_client.call_api(
                        '/block-devices', 'PUT')).to(
                            raise_api_exception(405, headers={'Allow': "GET"}))
示例#4
0
from mamba import description, before, after, it
from expects import *
import os

import client.api
import client.models
from common import Config, Service
from common.matcher import be_valid_port, raise_api_exception


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,'):
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.
        '''
示例#6
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']))
示例#7
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)
示例#8
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)))
示例#9
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'):
示例#10
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 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!'))
IRRELEVANT_PATH = spec_abspath('without_inner_contexts.py')
PENDING_DECORATOR_PATH = spec_abspath('with_pending_decorator.py')
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'))
示例#13
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()
示例#14
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))


示例#15
0
PENDING_DECORATOR_PATH = spec_abspath('with_pending_decorator.py')
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')
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'))
示例#16
0
        "Wed, 15 Jan 2020 21:19:15 -0500",
        "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')
示例#17
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)
示例#18
0
    return repository, new_file


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'):
# 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'}]))
示例#20
0
文件: tests.py 项目: b-steel/chess
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)
示例#21
0
文件: with_tags.py 项目: vicdoz/mamba
from mamba import description, it

with description('Fixture#with_tags', 'integration'):
    with it('first example', 'unit'):
        pass
示例#22
0

def generator_models(api_client):
    ports_api = client.api.PortsApi(api_client)
    ports = ports_api.list_ports()
    expect(ports).to(have_len(be_above(1)))

    gen1 = generator_model(api_client)
    gen1.target_id = ports[0].id
    gen2 = generator_model(api_client)
    gen2.target_id = ports[1].id

    return [gen1, gen2]


with description('Packet Generator,', 'packet_generator') as self:
    with description('REST API'):

        with before.all:
            service = Service(CONFIG.service())
            self.process = service.start()
            self.api = client.api.PacketGeneratorsApi(service.client())
            if not check_modules_exists(service.client(), 'packet-generator'):
                self.skip()

        with description('invalid HTTP methods,'):
            with description('/packet/generators,'):
                with it('returns 405'):
                    expect(lambda: self.api.api_client.call_api(
                        '/packet/generators', 'PUT')).to(
                            raise_api_exception(
示例#23
0
READ_ONLY_COMMUNITY = 'c4-temperatures'
READ_WRITE_COMMUNITY = 'set'
INVALID_COMMUNITY = 'a_community'
SNMP_HOST = '127.0.0.1'
SNMP_PORT = 1161


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(
示例#24
0
from mamba import description, before, after, it
from expects import *
import os

import client.api
import client.models
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(
示例#25
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))
示例#26
0
review_model = Review(id=1, review_id=REVIEW_UUID, text='scathing review - pigs cant talk', book_id=1)

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(
示例#27
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,
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))
    "fields": [], 
    "ruleNameRegEx": "%s", 
    "onDefault": "DEFAULT_MATCH_EFFECT_NEXT"
  }, 
  "policyEventsCount": 0,  
  "isManual": true, 
  "isBuiltin": true, 
  "containerScope": true, 
  "modifiedOn": 1597646118000, 
  "createdOn": 1597646118000
}
""" % (_POLICY_NAME, _POLICY_DESCRIPTION, json.dumps(_POLICY_ACTIONS),
       _POLICY_RULES_REGEX)


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"):
示例#30
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"))
        )
示例#31
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
示例#32
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)
示例#33
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)
示例#34
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))
示例#35
0
from kv import KVService as ThriftKVService

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())
示例#36
0
from types import MappingProxyType
from collections import deque
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)
示例#37
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))