Beispiel #1
0
 def object_(self, property_):
     object_ = Mock()
     type(object_).kind = PropertyMock(return_value='bovine')
     type(object_).slug = PropertyMock(return_value='cowslug')
     type(object_).properties = PropertyMock(return_value=[property_])
     return object_
Beispiel #2
0
def test_autodetect_category(release_type, exp_focused, bhd_tracker_jobs,
                             mocker):
    mocker.patch.object(type(bhd_tracker_jobs), 'release_name',
                        PropertyMock(return_value=Mock(type=release_type, )))
    bhd_tracker_jobs.autodetect_category('_')
    assert bhd_tracker_jobs.category_job.focused == exp_focused
Beispiel #3
0
def test_post_data_pack(approved_type, exp_pack, bhd_tracker_jobs, mocker):
    mocker.patch.object(type(bhd_tracker_jobs), 'release_name',
                        PropertyMock(return_value=Mock(type=approved_type, )))
    assert bhd_tracker_jobs.post_data_pack == exp_pack
Beispiel #4
0
def _mock_request(mocker: MockerFixture, body: str) -> MockerFixture:
    m = mocker.patch('requests.get')
    m.return_value = mocker.Mock(spec=requests.Response)
    txt = PropertyMock(return_value=body)
    type(m.return_value).text = txt
    return m
Beispiel #5
0
def test_api_status(botclient, mocker, ticker, fee, markets):
    ftbot, client = botclient
    patch_get_signal(ftbot, (True, False))
    mocker.patch.multiple(
        'freqtrade.exchange.Exchange',
        get_balances=MagicMock(return_value=ticker),
        fetch_ticker=ticker,
        get_fee=fee,
        markets=PropertyMock(return_value=markets),
        fetch_order=MagicMock(return_value={}),
    )

    rc = client_get(client, f"{BASE_URI}/status")
    assert_response(rc, 200)
    assert rc.json() == []
    create_mock_trades(fee)

    rc = client_get(client, f"{BASE_URI}/status")
    assert_response(rc)
    assert len(rc.json()) == 4
    assert rc.json()[0] == {
        'amount': 123.0,
        'amount_requested': 123.0,
        'close_date': None,
        'close_timestamp': None,
        'close_profit': None,
        'close_profit_pct': None,
        'close_profit_abs': None,
        'close_rate': None,
        'current_profit': ANY,
        'current_profit_pct': ANY,
        'current_profit_abs': ANY,
        'profit_ratio': ANY,
        'profit_pct': ANY,
        'profit_abs': ANY,
        'profit_fiat': ANY,
        'current_rate': 1.099e-05,
        'open_date': ANY,
        'open_timestamp': ANY,
        'open_order': None,
        'open_rate': 0.123,
        'pair': 'ETH/BTC',
        'stake_amount': 0.001,
        'stop_loss_abs': ANY,
        'stop_loss_pct': ANY,
        'stop_loss_ratio': ANY,
        'stoploss_order_id': None,
        'stoploss_last_update': ANY,
        'stoploss_last_update_timestamp': ANY,
        'initial_stop_loss_abs': 0.0,
        'initial_stop_loss_pct': ANY,
        'initial_stop_loss_ratio': ANY,
        'stoploss_current_dist': ANY,
        'stoploss_current_dist_ratio': ANY,
        'stoploss_current_dist_pct': ANY,
        'stoploss_entry_dist': ANY,
        'stoploss_entry_dist_ratio': ANY,
        'trade_id': 1,
        'close_rate_requested': ANY,
        'fee_close': 0.0025,
        'fee_close_cost': None,
        'fee_close_currency': None,
        'fee_open': 0.0025,
        'fee_open_cost': None,
        'fee_open_currency': None,
        'is_open': True,
        'max_rate': ANY,
        'min_rate': ANY,
        'open_order_id': 'dry_run_buy_12345',
        'open_rate_requested': ANY,
        'open_trade_value': 15.1668225,
        'sell_reason': None,
        'sell_order_status': None,
        'strategy': 'DefaultStrategy',
        'timeframe': 5,
        'exchange': 'bittrex',
    }

    mocker.patch(
        'freqtrade.freqtradebot.FreqtradeBot.get_sell_rate',
        MagicMock(side_effect=ExchangeError("Pair 'ETH/BTC' not available")))

    rc = client_get(client, f"{BASE_URI}/status")
    assert_response(rc)
    resp_values = rc.json()
    assert len(resp_values) == 4
    assert isnan(resp_values[0]['profit_abs'])
Beispiel #6
0
def test_list_markets(mocker, markets, capsys):

    api_mock = MagicMock()
    api_mock.markets = markets
    patch_exchange(mocker, api_mock=api_mock)

    # Test with no --config
    args = [
        "list-markets",
    ]
    pargs = get_args(args)
    pargs['config'] = None
    with pytest.raises(OperationalException,
                       match=r"This command requires a configured exchange.*"):
        start_list_markets(pargs, False)

    # Test with --config config_bittrex.json.example
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert ("Exchange Bittrex has 10 active markets: "
            "BLK/BTC, ETH/BTC, ETH/USDT, LTC/BTC, LTC/ETH, LTC/USD, NEO/BTC, "
            "TKN/BTC, XLTCUSDT, XRP/BTC.\n" in captured.out)

    patch_exchange(mocker, api_mock=api_mock, id="binance")
    # Test with --exchange
    args = ["list-markets", "--exchange", "binance"]
    pargs = get_args(args)
    pargs['config'] = None
    start_list_markets(pargs, False)
    captured = capsys.readouterr()
    assert re.match("\nExchange Binance has 10 active markets:\n",
                    captured.out)

    patch_exchange(mocker, api_mock=api_mock, id="bittrex")
    # Test with --all: all markets
    args = [
        "list-markets",
        "--all",
        '--config',
        'config_bittrex.json.example',
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 12 markets: "
        "BLK/BTC, BTT/BTC, ETH/BTC, ETH/USDT, LTC/BTC, LTC/ETH, LTC/USD, LTC/USDT, NEO/BTC, "
        "TKN/BTC, XLTCUSDT, XRP/BTC.\n" in captured.out)

    # Test list-pairs subcommand: active pairs
    args = [
        "list-pairs",
        '--config',
        'config_bittrex.json.example',
        "--print-list",
    ]
    start_list_markets(get_args(args), True)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 9 active pairs: "
        "BLK/BTC, ETH/BTC, ETH/USDT, LTC/BTC, LTC/ETH, LTC/USD, NEO/BTC, TKN/BTC, XRP/BTC.\n"
        in captured.out)

    # Test list-pairs subcommand with --all: all pairs
    args = [
        "list-pairs",
        "--all",
        '--config',
        'config_bittrex.json.example',
        "--print-list",
    ]
    start_list_markets(get_args(args), True)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 11 pairs: "
        "BLK/BTC, BTT/BTC, ETH/BTC, ETH/USDT, LTC/BTC, LTC/ETH, LTC/USD, LTC/USDT, NEO/BTC, "
        "TKN/BTC, XRP/BTC.\n" in captured.out)

    # active markets, base=ETH, LTC
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--base",
        "ETH",
        "LTC",
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 6 active markets with ETH, LTC as base currencies: "
        "ETH/BTC, ETH/USDT, LTC/BTC, LTC/ETH, LTC/USD, XLTCUSDT.\n"
        in captured.out)

    # active markets, base=LTC
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--base",
        "LTC",
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert ("Exchange Bittrex has 4 active markets with LTC as base currency: "
            "LTC/BTC, LTC/ETH, LTC/USD, XLTCUSDT.\n" in captured.out)

    # active markets, quote=USDT, USD
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--quote",
        "USDT",
        "USD",
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 3 active markets with USDT, USD as quote currencies: "
        "ETH/USDT, LTC/USD, XLTCUSDT.\n" in captured.out)

    # active markets, quote=USDT
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--quote",
        "USDT",
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 2 active markets with USDT as quote currency: "
        "ETH/USDT, XLTCUSDT.\n" in captured.out)

    # active markets, base=LTC, quote=USDT
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--base",
        "LTC",
        "--quote",
        "USDT",
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 1 active market with LTC as base currency and "
        "with USDT as quote currency: XLTCUSDT.\n" in captured.out)

    # active pairs, base=LTC, quote=USDT
    args = [
        "list-pairs",
        '--config',
        'config_bittrex.json.example',
        "--base",
        "LTC",
        "--quote",
        "USD",
        "--print-list",
    ]
    start_list_markets(get_args(args), True)
    captured = capsys.readouterr()
    assert ("Exchange Bittrex has 1 active pair with LTC as base currency and "
            "with USD as quote currency: LTC/USD.\n" in captured.out)

    # active markets, base=LTC, quote=USDT, NONEXISTENT
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--base",
        "LTC",
        "--quote",
        "USDT",
        "NONEXISTENT",
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 1 active market with LTC as base currency and "
        "with USDT, NONEXISTENT as quote currencies: XLTCUSDT.\n"
        in captured.out)

    # active markets, base=LTC, quote=NONEXISTENT
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--base",
        "LTC",
        "--quote",
        "NONEXISTENT",
        "--print-list",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 0 active markets with LTC as base currency and "
        "with NONEXISTENT as quote currency.\n" in captured.out)

    # Test tabular output
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert ("Exchange Bittrex has 10 active markets:\n" in captured.out)

    # Test tabular output, no markets found
    args = [
        "list-markets",
        '--config',
        'config_bittrex.json.example',
        "--base",
        "LTC",
        "--quote",
        "NONEXISTENT",
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        "Exchange Bittrex has 0 active markets with LTC as base currency and "
        "with NONEXISTENT as quote currency.\n" in captured.out)

    # Test --print-json
    args = [
        "list-markets", '--config', 'config_bittrex.json.example',
        "--print-json"
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert (
        '["BLK/BTC","ETH/BTC","ETH/USDT","LTC/BTC","LTC/ETH","LTC/USD","NEO/BTC",'
        '"TKN/BTC","XLTCUSDT","XRP/BTC"]' in captured.out)

    # Test --print-csv
    args = [
        "list-markets", '--config', 'config_bittrex.json.example',
        "--print-csv"
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert ("Id,Symbol,Base,Quote,Active,Is pair" in captured.out)
    assert ("blkbtc,BLK/BTC,BLK,BTC,True,True" in captured.out)
    assert ("USD-LTC,LTC/USD,LTC,USD,True,True" in captured.out)

    # Test --one-column
    args = [
        "list-markets", '--config', 'config_bittrex.json.example',
        "--one-column"
    ]
    start_list_markets(get_args(args), False)
    captured = capsys.readouterr()
    assert re.search(r"^BLK/BTC$", captured.out, re.MULTILINE)
    assert re.search(r"^LTC/USD$", captured.out, re.MULTILINE)

    mocker.patch('freqtrade.exchange.Exchange.markets',
                 PropertyMock(side_effect=ValueError))
    # Test --one-column
    args = [
        "list-markets", '--config', 'config_bittrex.json.example',
        "--one-column"
    ]
    with pytest.raises(OperationalException, match=r"Cannot get markets.*"):
        start_list_markets(get_args(args), False)
Beispiel #7
0
def test_api_status(botclient, mocker, ticker, fee, markets):
    ftbot, client = botclient
    patch_get_signal(ftbot, (True, False))
    mocker.patch.multiple('freqtrade.exchange.Exchange',
                          get_balances=MagicMock(return_value=ticker),
                          fetch_ticker=ticker,
                          get_fee=fee,
                          markets=PropertyMock(return_value=markets))

    rc = client_get(client, f"{BASE_URI}/status")
    assert_response(rc, 200)
    assert rc.json == []

    ftbot.enter_positions()
    rc = client_get(client, f"{BASE_URI}/status")
    assert_response(rc)
    assert len(rc.json) == 1
    assert rc.json == [{
        'amount': 91.07468124,
        'base_currency': 'BTC',
        'close_date': None,
        'close_date_hum': None,
        'close_timestamp': None,
        'close_profit': None,
        'close_profit_pct': None,
        'close_rate': None,
        'current_profit': -0.00408133,
        'current_profit_pct': -0.41,
        'current_rate': 1.099e-05,
        'initial_stop_loss': 0.0,
        'initial_stop_loss_pct': None,
        'open_date': ANY,
        'open_date_hum': 'just now',
        'open_timestamp': ANY,
        'open_order': '(limit buy rem=0.00000000)',
        'open_rate': 1.098e-05,
        'pair': 'ETH/BTC',
        'stake_amount': 0.001,
        'stop_loss': 0.0,
        'stop_loss_pct': None,
        'trade_id': 1,
        'close_rate_requested': None,
        'current_rate': 1.099e-05,
        'fee_close': 0.0025,
        'fee_close_cost': None,
        'fee_close_currency': None,
        'fee_open': 0.0025,
        'fee_open_cost': None,
        'fee_open_currency': None,
        'open_date': ANY,
        'is_open': True,
        'max_rate': 0.0,
        'min_rate': None,
        'open_order_id': ANY,
        'open_rate_requested': 1.098e-05,
        'open_trade_price': 0.0010025,
        'sell_reason': None,
        'sell_order_status': None,
        'strategy': 'DefaultStrategy',
        'ticker_interval': 5
    }]
Beispiel #8
0
 def test_deduplicates_labels(self, inst):
     type(inst).default_labels = PropertyMock(return_value=["label1"])
     assert sorted(inst.labels) == ["label1", "label2"]
Beispiel #9
0
 def __init__(self):
     self.args = PropertyMock()
    def setUp(self):
        MemoryStorage.is_public = PropertyMock(return_value=True)

        self.api = Facebook('')
        self.storage = MemoryStorage()
Beispiel #11
0
class TestMicrosoftFaceIdentify(object):
    """Test class for image processing."""
    def setup_method(self):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()

        self.config = {
            ip.DOMAIN: {
                'platform': 'microsoft_face_identify',
                'source': {
                    'entity_id': 'camera.demo_camera',
                    'name': 'test local'
                },
                'group': 'Test Group1',
            },
            'camera': {
                'platform': 'demo'
            },
            mf.DOMAIN: {
                'api_key': '12345678abcdef6',
            }
        }

    def teardown_method(self):
        """Stop everything that was started."""
        self.hass.stop()

    @patch('homeassistant.components.image_processing.microsoft_face_identify.'
           'MicrosoftFaceIdentifyEntity.should_poll',
           new_callable=PropertyMock(return_value=False))
    def test_openalpr_process_image(self, poll_mock, aioclient_mock):
        """Setup and scan a picture and test plates from event."""
        aioclient_mock.get(
            mf.FACE_API_URL.format("persongroups"),
            text=load_fixture('microsoft_face_persongroups.json'))
        aioclient_mock.get(
            mf.FACE_API_URL.format("persongroups/test_group1/persons"),
            text=load_fixture('microsoft_face_persons.json'))
        aioclient_mock.get(
            mf.FACE_API_URL.format("persongroups/test_group2/persons"),
            text=load_fixture('microsoft_face_persons.json'))

        setup_component(self.hass, ip.DOMAIN, self.config)

        state = self.hass.states.get('camera.demo_camera')
        url = "{0}{1}".format(self.hass.config.api.base_url,
                              state.attributes.get(ATTR_ENTITY_PICTURE))

        face_events = []

        @callback
        def mock_face_event(event):
            """Mock event."""
            face_events.append(event)

        self.hass.bus.listen('identify_face', mock_face_event)

        aioclient_mock.get(url, content=b'image')

        aioclient_mock.post(mf.FACE_API_URL.format("detect"),
                            text=load_fixture('microsoft_face_detect.json'))
        aioclient_mock.post(mf.FACE_API_URL.format("identify"),
                            text=load_fixture('microsoft_face_identify.json'))

        ip.scan(self.hass, entity_id='image_processing.test_local')
        self.hass.block_till_done()

        state = self.hass.states.get('image_processing.test_local')

        assert len(face_events) == 1
        assert state.attributes.get('total_faces') == 2
        assert state.state == 'David'

        assert face_events[0].data['name'] == 'David'
        assert face_events[0].data['confidence'] == float(92)
        assert face_events[0].data['entity_id'] == \
            'image_processing.test_local'
async def test_alarm_control_panel(opp, canary) -> None:
    """Test the creation and values of the alarm_control_panel for Canary."""
    await async_setup_component(opp, "persistent_notification", {})

    registry = mock_registry(opp)
    online_device_at_home = mock_device(20, "Dining Room", True, "Canary Pro")

    mocked_location = mock_location(
        location_id=100,
        name="Home",
        is_celsius=True,
        is_private=False,
        mode=mock_mode(7, "standby"),
        devices=[online_device_at_home],
    )

    instance = canary.return_value
    instance.get_locations.return_value = [mocked_location]

    config = {DOMAIN: {"username": "******", "password": "******"}}
    with patch("openpeerpower.components.canary.PLATFORMS", ["alarm_control_panel"]):
        assert await async_setup_component(opp, DOMAIN, config)
        await opp.async_block_till_done()

    entity_id = "alarm_control_panel.home"
    entity_entry = registry.async_get(entity_id)
    assert entity_entry
    assert entity_entry.unique_id == "100"

    state = opp.states.get(entity_id)
    assert state
    assert state.state == STATE_UNKNOWN
    assert not state.attributes["private"]

    # test private system
    type(mocked_location).is_private = PropertyMock(return_value=True)

    await opp.helpers.entity_component.async_update_entity(entity_id)
    await opp.async_block_till_done()

    state = opp.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_DISARMED
    assert state.attributes["private"]

    type(mocked_location).is_private = PropertyMock(return_value=False)

    # test armed home
    type(mocked_location).mode = PropertyMock(
        return_value=mock_mode(4, LOCATION_MODE_HOME)
    )

    await opp.helpers.entity_component.async_update_entity(entity_id)
    await opp.async_block_till_done()

    state = opp.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_ARMED_HOME

    # test armed away
    type(mocked_location).mode = PropertyMock(
        return_value=mock_mode(5, LOCATION_MODE_AWAY)
    )

    await opp.helpers.entity_component.async_update_entity(entity_id)
    await opp.async_block_till_done()

    state = opp.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_ARMED_AWAY

    # test armed night
    type(mocked_location).mode = PropertyMock(
        return_value=mock_mode(6, LOCATION_MODE_NIGHT)
    )

    await opp.helpers.entity_component.async_update_entity(entity_id)
    await opp.async_block_till_done()

    state = opp.states.get(entity_id)
    assert state
    assert state.state == STATE_ALARM_ARMED_NIGHT
Beispiel #13
0
 def additional_properties(self, additional_instance):
     property_ = Mock()
     type(property_).label = PropertyMock(return_value='name')
     type(property_).instances = PropertyMock(
         return_value=[additional_instance])
     return [property_]
Beispiel #14
0
 def property_(self, instance):
     property_ = Mock()
     type(property_).label = PropertyMock(return_value='The cow says')
     type(property_).instances = PropertyMock(return_value=[instance])
     return property_
Beispiel #15
0
 async def test_handle_message_radarr_and_sonarr_channel(self, mock_search_multi, mock_config):
     mock_search_multi.return_value = []
     type(mock_config).SONARR_CHANNELS = PropertyMock(return_value=[ self.test_channel ])
     type(mock_config).RADARR_CHANNELS = PropertyMock(return_value=[ self.test_channel ])
     reply = await search.handle_message('', self.mock_message())
     mock_search_multi.assert_called_with('', ['tv', 'movie'])
Beispiel #16
0
"""LDAP Source tests"""
from unittest.mock import PropertyMock, patch

from django.test import TestCase

from authentik.core.models import User
from authentik.lib.generators import generate_key
from authentik.sources.ldap.models import LDAPPropertyMapping, LDAPSource
from authentik.sources.ldap.password import LDAPPasswordChanger
from authentik.sources.ldap.tests.mock_ad import mock_ad_connection

LDAP_PASSWORD = generate_key()
LDAP_CONNECTION_PATCH = PropertyMock(
    return_value=mock_ad_connection(LDAP_PASSWORD))


class LDAPPasswordTests(TestCase):
    """LDAP Password tests"""
    def setUp(self):
        self.source = LDAPSource.objects.create(
            name="ldap",
            slug="ldap",
            base_dn="dc=goauthentik,dc=io",
            additional_user_dn="ou=users",
            additional_group_dn="ou=groups",
        )
        self.source.property_mappings.set(LDAPPropertyMapping.objects.all())
        self.source.save()

    @patch("authentik.sources.ldap.models.LDAPSource.connection",
           LDAP_CONNECTION_PATCH)
Beispiel #17
0
from unittest.mock import MagicMock, PropertyMock

m = MagicMock()
type(m).foo = PropertyMock(side_effect=[1, 2])

print(m.foo)
print(m.foo)

# Another solution
# p = PropertyMock(side_effect=[1, 2])
# type(m).foo = p
Beispiel #18
0
def fake_get_error(url, **kwargs):
    response = MagicMock()
    type(response).status_code = PropertyMock(return_value=400)
    response.json.return_value = {}
    return response
Beispiel #19
0
def mocked_failed_response(error: Exception, status_code: int = 200) -> Mock:
    m = Mock(json=Mock(side_effect=error), status_code=status_code)

    type(m).content = PropertyMock(side_effect=error)
    return m
Beispiel #20
0
def fake_post(url, data=None, json=None, **kwargs):
    response = Mock(spec=Response)
    type(response).status_code = PropertyMock(return_value=200)
    response.json.return_value = {}
    return response
Beispiel #21
0
 def test_wait_until_window_closes_with_timeout(self, robot_call):
     mock_gui = Mock()
     type(mock_gui).timeout = PropertyMock(return_value=15)
     GUILibrary.wait_until_window_closes(mock_gui, "title", 6)
     robot_call.assert_called_with(6, 1, "Window Should Not Be Open",
                                   "title")
Beispiel #22
0
 def _reset_message(context):
     message = MagicMock()
     type(message).message_id = PropertyMock(return_value=1003)
     context.send_response_message.reset_mock()
     context.send_response_message.return_value = message
     context.update.callback_query.edit_message_text.reset_mock()
def test_filter_out_cherrypicked_samples_returns_input_samples_with_empty_cp_samples_df(config, testing_samples):
    cp_samples_df = MagicMock()
    type(cp_samples_df).empty = PropertyMock(return_value=True)
    with patch("crawler.helpers.cherrypicked_samples.get_cherrypicked_samples", return_value=cp_samples_df):
        result = filter_out_cherrypicked_samples(config, testing_samples)
        assert result == testing_samples
Beispiel #24
0
    def test_recall_accept_decline(self):
        with ScopedSession(self.connection) as session:
            context = self._create_context(session)
            other_users = [
                User(id=i, name='user ' + str(i)) for i in range(1, 4)
            ]
            for user in other_users:
                context.group.users.append(user)
                session.add(user)

            # Initial call.
            self._reset_message(context)
            broadcasts.on_recall_request(context)
            context.send_response_message.assert_called_once_with(
                'recall_from_sender\n\nrecall_not_answered_user 1, user 2, user 3',
                reply_markup=self.MatcherResponseKeyboard())
            self.assertEqual(1, session.query(Request).count())
            request = session.query(Request).first()

            # First user accepted.
            self._reset_message(context)
            type(context).sender = PropertyMock(return_value=other_users[0])
            type(context.update.callback_query.message
                 ).message_id = PropertyMock(return_value=request.message_id)
            broadcasts.on_recall_join(context)
            context.update.callback_query.edit_message_text.assert_called_once_with(
                text=
                'recall_from_sender\n\nrecall_joined_user 1\nrecall_not_answered_user 2, user 3',
                reply_markup=self.MatcherResponseKeyboard())
            self.assertEqual(1, session.query(Response).count())

            # Second user declined.
            self._reset_message(context)
            type(context).sender = PropertyMock(return_value=other_users[1])
            broadcasts.on_recall_decline(context)
            context.update.callback_query.edit_message_text.assert_called_once_with(
                text=
                'recall_from_sender\n\nrecall_joined_user 1\nrecall_declined_user 2\nrecall_not_answered_user 3',
                reply_markup=self.MatcherResponseKeyboard())
            self.assertEqual(2, session.query(Response).count())

            # First user declined too.
            self._reset_message(context)
            type(context).sender = PropertyMock(return_value=other_users[0])
            broadcasts.on_recall_decline(context)
            context.update.callback_query.edit_message_text.assert_called_once_with(
                text=
                'recall_from_sender\n\nrecall_declined_user 1, user 2\nrecall_not_answered_user 3',
                reply_markup=self.MatcherResponseKeyboard())
            self.assertEqual(2, session.query(Response).count())

            # Message became obsolete and can not be updated.
            self._reset_message(context)
            context.update.callback_query.edit_message_text.side_effect = TelegramError(
                '')
            broadcasts.on_recall_join(context)
            context.update.callback_query.edit_message_text.assert_called_once_with(
                text=
                'recall_from_sender\n\nrecall_joined_user 1\nrecall_declined_user 2\nrecall_not_answered_user 3',
                reply_markup=self.MatcherResponseKeyboard())
            context.send_response_message.assert_called_once_with(
                'invalid_request_user 1')
            self.assertEqual(2, session.query(Response).count())
Beispiel #25
0
def test_isolated_jobs(options, exp_isolated_jobs, bhd_tracker_jobs, mocker):
    mocker.patch.object(type(bhd_tracker_jobs), 'options',
                        PropertyMock(return_value=options))
    assert bhd_tracker_jobs.isolated_jobs == exp_isolated_jobs
Beispiel #26
0
class TestFeatureObservationsReportView(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        feature_class = FeatureClassFactory(www=True)
        self.feature = FeatureFactory(
            feature_class=feature_class,
            protection_level=PROTECTION_LEVELS["PUBLIC"],
        )
        self.observation_admin = ObservationFactory(
            protection_level=PROTECTION_LEVELS["ADMIN"],
            feature=self.feature,
        )
        self.observation_office = ObservationFactory(
            protection_level=PROTECTION_LEVELS["OFFICE"],
            feature=self.feature,
        )
        self.observation_www = ObservationFactory(
            protection_level=PROTECTION_LEVELS["PUBLIC"],
            feature=self.feature,
        )

    @patch(
        "nature.views.HMACAuth.user_role",
        new_callable=PropertyMock(return_value=UserRole.ADMIN),
    )
    def test_get_context_data_for_admin(self, *args):
        view = FeatureObservationsReportView()
        view_kwargs = {"pk": self.feature.pk}
        request = self.factory.get(
            reverse("nature:feature-observations-report", kwargs=view_kwargs)
        )
        request.user = AnonymousUser()
        view.request = request
        view.object = self.feature

        context = view.get_context_data()
        self.assertQuerysetEqual(
            context["observations"],
            [
                repr(self.observation_admin),
                repr(self.observation_office),
                repr(self.observation_www),
            ],
            ordered=False,
        )
        self.assertEqual(context["secret_observation_count"], 0)

    @patch(
        "nature.views.HMACAuth.user_role",
        new_callable=PropertyMock(return_value=UserRole.OFFICE_HKI),
    )
    def test_get_context_data_for_office_hki(self, *args):
        view = FeatureObservationsReportView()
        view_kwargs = {"pk": self.feature.pk}
        request = self.factory.get(
            reverse("nature:feature-observations-report", kwargs=view_kwargs)
        )
        request.user = AnonymousUser()
        view.request = request
        view.object = self.feature

        context = view.get_context_data()
        self.assertQuerysetEqual(
            context["observations"],
            [repr(self.observation_office), repr(self.observation_www)],
            ordered=False,
        )
        self.assertEqual(context["secret_observation_count"], 1)

    @patch(
        "nature.views.HMACAuth.user_role",
        new_callable=PropertyMock(return_value=UserRole.OFFICE),
    )
    def test_get_context_data_for_office(self, *args):
        view = FeatureObservationsReportView()
        view_kwargs = {"pk": self.feature.pk}
        request = self.factory.get(
            reverse("nature:feature-observations-report", kwargs=view_kwargs)
        )
        request.user = AnonymousUser()
        view.request = request
        view.object = self.feature

        context = view.get_context_data()
        self.assertQuerysetEqual(
            context["observations"],
            [repr(self.observation_office), repr(self.observation_www)],
            ordered=False,
        )
        self.assertEqual(context["secret_observation_count"], 1)

    @patch(
        "nature.views.HMACAuth.user_role",
        new_callable=PropertyMock(return_value=UserRole.PUBLIC),
    )
    def test_get_context_data_for_public_www(self, *args):
        view = FeatureObservationsReportView()
        view_kwargs = {"pk": self.feature.pk}
        request = self.factory.get(
            reverse("nature:feature-observations-report", kwargs=view_kwargs)
        )
        request.user = AnonymousUser()
        view.request = request
        view.object = self.feature

        context = view.get_context_data()
        self.assertQuerysetEqual(
            context["observations"],
            [repr(self.observation_www)],
            ordered=False,
        )
        self.assertEqual(context["secret_observation_count"], 0)
Beispiel #27
0
def test_post_data(anonymous, exp_anon, draft, exp_live, bhd_tracker_jobs,
                   mock_job_attributes, mocker):
    mock_job_attributes(bhd_tracker_jobs)
    mocker.patch.object(bhd_tracker_jobs,
                        'get_job_output',
                        side_effect=(
                            'mock release name',
                            'tt00123456',
                            'movie/1234',
                            'mock description',
                            'Some\nMock\nTags',
                        ))
    mocker.patch.object(bhd_tracker_jobs,
                        'get_job_attribute',
                        side_effect=(
                            'mock category',
                            'mock type',
                            'mock source',
                        ))
    mocker.patch.object(
        type(bhd_tracker_jobs), 'options',
        PropertyMock(
            return_value={
                'custom_edition': 'mock custom edition',
                'anonymous': anonymous,
                'draft': draft,
            }))
    mocker.patch.object(type(bhd_tracker_jobs), 'post_data_edition',
                        PropertyMock(return_value='mock edition'))
    mocker.patch.object(type(bhd_tracker_jobs), 'post_data_nfo',
                        PropertyMock(return_value='mock nfo'))
    mocker.patch.object(type(bhd_tracker_jobs), 'post_data_pack',
                        PropertyMock(return_value='mock pack'))
    mocker.patch.object(type(bhd_tracker_jobs), 'post_data_sd',
                        PropertyMock(return_value='mock sd'))
    mocker.patch.object(type(bhd_tracker_jobs), 'post_data_special',
                        PropertyMock(return_value='mock special'))

    assert bhd_tracker_jobs.post_data == {
        'name': 'mock release name',
        'category_id': 'mock category',
        'type': 'mock type',
        'source': 'mock source',
        'imdb_id': 'tt00123456',
        'tmdb_id': '1234',
        'description': 'mock description',
        'edition': 'mock edition',
        'custom_edition': 'mock custom edition',
        'tags': 'Some,Mock,Tags',
        'nfo': 'mock nfo',
        'pack': 'mock pack',
        'sd': 'mock sd',
        'special': 'mock special',
        'anon': exp_anon,
        'live': exp_live,
    }
    assert bhd_tracker_jobs.get_job_output.call_args_list == [
        call(bhd_tracker_jobs.release_name_job, slice=0),
        call(bhd_tracker_jobs.imdb_job, slice=0),
        call(bhd_tracker_jobs.tmdb_job, slice=0),
        call(bhd_tracker_jobs.description_job, slice=0),
        call(bhd_tracker_jobs.tags_job, slice=0),
    ]
    assert bhd_tracker_jobs.get_job_attribute.call_args_list == [
        call(bhd_tracker_jobs.category_job, 'choice'),
        call(bhd_tracker_jobs.type_job, 'choice'),
        call(bhd_tracker_jobs.source_job, 'choice'),
    ]
Beispiel #28
0
    def test_assign_cmd(self):
        plugins.labhub.GitHub = create_autospec(IGitt.GitHub.GitHub.GitHub)
        plugins.labhub.GitLab = create_autospec(IGitt.GitLab.GitLab.GitLab)
        labhub, testbot = plugin_testbot(plugins.labhub.LabHub, logging.ERROR)
        labhub.activate()

        mock_issue = create_autospec(GitHubIssue)
        self.mock_repo.get_issue.return_value = mock_issue

        labhub.REPOS = {'a': self.mock_repo}

        mock_dev_team = create_autospec(github3.orgs.Team)
        mock_maint_team = create_autospec(github3.orgs.Team)
        mock_dev_team.is_member.return_value = False
        mock_maint_team.is_member.return_value = False

        labhub.TEAMS = {
            'coala newcomers': self.mock_team,
            'coala developers': mock_dev_team,
            'coala maintainers': mock_maint_team
        }

        cmd = '!assign https://github.com/{}/{}/issues/{}'
        # no assignee, not newcomer
        mock_issue.assignees = tuple()
        self.mock_team.is_member.return_value = False

        testbot.assertCommand(cmd.format('coala', 'a', '23'),
                              'You\'ve been assigned to the issue')

        # no assignee, newcomer, difficulty/low
        mock_issue.labels = PropertyMock()
        mock_issue.labels = ('difficulty/low', )
        mock_issue.assignees = tuple()
        self.mock_team.is_member.return_value = True

        testbot.assertCommand(cmd.format('coala', 'a', '23'),
                              'You\'ve been assigned to the issue')

        # no assignee, newcomer, no labels
        self.mock_team.is_member.return_value = True
        mock_issue.labels = tuple()
        mock_issue.assignees = tuple()
        testbot.assertCommand(cmd.format('coala', 'a', '23'),
                              'not eligible to be assigned to this issue')
        testbot.pop_message()

        # no assignee, newcomer, difficulty medium
        mock_issue.labels = ('difficulty/medium', )
        testbot.assertCommand(cmd.format('coala', 'a', '23'),
                              'not eligible to be assigned to this issue')
        testbot.pop_message()

        # no assignee, newcomer, difficulty medium
        labhub.GH_ORG_NAME = 'not-coala'
        testbot.assertCommand(cmd.format('coala', 'a', '23'), 'assigned')
        labhub.GH_ORG_NAME = 'coala'

        # newcomer, developer, difficulty/medium
        mock_dev_team.is_member.return_value = True
        mock_maint_team.is_member.return_value = False
        testbot.assertCommand(cmd.format('coala', 'a', '23'), 'assigned')

        # has assignee
        mock_issue.assignees = ('somebody', )
        testbot.assertCommand(cmd.format('coala', 'a', '23'),
                              'already assigned to someone')

        # has assignee same as user
        mock_issue.assignees = (None, )
        testbot.assertCommand(cmd.format('coala', 'a', '23'),
                              'already assigned to you')

        # non-existent repository
        testbot.assertCommand(cmd.format('coala', 'c', '23'),
                              'Repository doesn\'t exist.')

        # unknown org
        testbot.assertCommand(cmd.format('coa', 'a', '23'),
                              'Repository not owned by our org.')
Beispiel #29
0
def test_post_data_sd(resolution, exp_sd, bhd_tracker_jobs, mocker):
    mocker.patch.object(
        type(bhd_tracker_jobs), 'release_name',
        PropertyMock(return_value=Mock(resolution=resolution, )))
    assert bhd_tracker_jobs.post_data_sd == exp_sd
Beispiel #30
0
 def additional_instance(self):
     instance = Mock()
     type(instance).value = PropertyMock(return_value='aloysius')
     return instance