Exemplo n.º 1
0
 def setUp(self):
     self.discord_user = USER_WITH_SAME_SERVER
     self.faker = Faker()
     self.data = {
         'discord_user_id': self.discord_user,
         'message_content': self.faker.word(),
     }
     self.url = reverse('bot:utils:send_message')
Exemplo n.º 2
0
class TestOilAndRopeException(TestCase):
    exception = OilAndRopeException

    def setUp(self):
        self.faker = Faker()

    def test_message_ok(self):
        msg = self.faker.word()
        ex = self.exception(msg)

        self.assertEqual(msg, ex.message)

    def test_message_no_format_ok(self):
        msg = self.faker.word()
        ex = self.exception(msg)

        self.assertEqual(msg, ex.message_no_format)
Exemplo n.º 3
0
class TestSendMessageToDiscordUserView(TestCase):
    def setUp(self):
        self.discord_user = USER_WITH_SAME_SERVER
        self.faker = Faker()
        self.data = {
            'discord_user_id': self.discord_user,
            'message_content': self.faker.word(),
        }
        self.url = reverse('bot:utils:send_message')

    def test_post_ok(self):
        response = self.client.post(self.url, data=self.data)

        self.assertEqual(201, response.status_code)

    def test_post_missing_data_ko(self):
        response = self.client.post(self.url, data={})

        self.assertEqual(400, response.status_code)

    @override_settings(ALLOWED_HOSTS=['localhost', 'testserver', '127.0.0.1'])
    def test_post_from_outer_ko(self):
        response = self.client.post(self.url,
                                    data=self.data,
                                    REMOTE_ADDR=self.faker.ipv4())

        self.assertEqual(403, response.status_code)

    @override_settings(
        ALLOWED_HOSTS=['develop.oilandrope-project.com', 'testserver'])
    def test_post_from_outer_ok(self):
        response = self.client.post(
            self.url,
            data=self.data,
            HTTP_ORIGIN='http://develop.oilandrope-project.com')

        self.assertEqual(201, response.status_code)

    def test_post_msg_created_ok(self):
        response = self.client.post(self.url, data=self.data)
        channel = Channel(response.json()['channel_id'])
        msg = Message(channel, response.json()['id'])

        self.assertEqual(response.json(), msg.json_response)
Exemplo n.º 4
0
def test_raise_error_if_add_task_assigns_unvalid_agile_state(
        task_attributes: Dict[str, str], faker: Faker) -> None:
    """
    Given: Nothing
    When: A Task is initialized with an invalid agile state
    Then: ValueError is raised
    """
    task_attributes["state"] = faker.word()

    with pytest.raises(
            ValidationError,
            match=
            "value is not a valid enumeration member; permitted: 'backlog'",
    ):
        Task(**task_attributes)
Exemplo n.º 5
0
def test_add_recurrent_task_raises_exception_if_recurrence_type_is_incorrect(
    task_attributes: Dict[str, str],
    faker: Faker,
) -> None:
    """
    Given: The task attributes of a recurrent task with a wrong recurrence_type
    When: A RecurrentTask is initialized.
    Then: TaskAttributeError exception is raised.
    """
    task_attributes = {
        **task_attributes,
        "due": faker.date_time(),
        "recurrence": "1d",
        "recurrence_type": "inexistent_recurrence_type",
    }

    with pytest.raises(
            ValidationError,
            match=
            "value is not a valid enumeration member; permitted: 'recurring'",
    ):
        RecurrentTask(**task_attributes)
Exemplo n.º 6
0
def other_project_id(faker: Faker, user_project: Dict[str, Any]) -> UUIDStr:
    other_id = faker.uuid4()
    assert user_project["uuid"] != other_id
    return other_id
Exemplo n.º 7
0
def client_session_id(faker: Faker) -> UUIDStr:
    return faker.uuid4()
Exemplo n.º 8
0
def node_uuid(faker: Faker) -> str:
    return faker.uuid4()
Exemplo n.º 9
0
def user_id(faker: Faker) -> int:
    return faker.pyint(min_value=1)
Exemplo n.º 10
0
 def setUp(self):
     self.faker = Faker()
     self.users_url = f'{settings.DISCORD_API_URL}users'
     self.bot_url = f'{self.users_url}/@me'
     self.dm_url = f'{self.users_url}/@me/channels'
     self.channels_url = f'{settings.DISCORD_API_URL}channels'
Exemplo n.º 11
0
class TestDiscordApiRequest(TestCase):
    def setUp(self):
        self.faker = Faker()
        self.users_url = f'{settings.DISCORD_API_URL}users'
        self.bot_url = f'{self.users_url}/@me'
        self.dm_url = f'{self.users_url}/@me/channels'
        self.channels_url = f'{settings.DISCORD_API_URL}channels'

    def test_discord_api_get_ok(self):
        url = f'{self.users_url}/{USER_WITH_SAME_SERVER}'
        response = discord_api_get(url)

        self.assertEqual(200, response.status_code)

    def test_discord_api_get_ko(self):
        url = f'{self.dm_url}/{self.faker.pyint(min_value=1)}'

        with self.assertRaises(DiscordApiException) as ex:
            discord_api_get(url)
        ex = ex.exception
        self.assertEqual(404, ex.error_code)

    def test_discord_api_post_ok(self):
        data = {'recipient_id': USER_WITH_SAME_SERVER}
        response = discord_api_post(f'{self.dm_url}', data=data)

        self.assertEqual(200, response.status_code)

    # Accessing unexistent user as bot
    @override_settings(BOT_TOKEN='this_is_an_unexistent_token')
    def test_discord_api_post_ko(self):
        data = {'recipient_id': USER_WITH_DIFFERENT_SERVER}

        with self.assertRaises(DiscordApiException) as ex:
            discord_api_post(f'{self.dm_url}', data=data)
        ex = ex.exception
        self.assertEqual(401, ex.error_code)

    def test_discord_api_patch_ok(self):
        url = f'{self.channels_url}/{CHANNEL}'
        msg_url = f'{url}/messages'
        msg_json = discord_api_post(msg_url,
                                    data={
                                        'content': self.faker.word()
                                    }).json()
        msg_id = msg_json['id']
        url = f'{msg_url}/{msg_id}'
        response = discord_api_patch(url, data={'content': self.faker.word()})

        self.assertEqual(200, response.status_code)

    def test_discord_api_patch_ko(self):
        url = f'{self.channels_url}/{CHANNEL}/messages/{self.faker.pyint(min_value=1)}'

        with self.assertRaises(DiscordApiException) as ex:
            discord_api_patch(url, data={'content': self.faker.word()})
        ex = ex.exception
        self.assertEqual(ex.error_code, 403)

    def test_internal_server_error(self):
        url = f'{self.dm_url}'
        data = {'recipient_id': self.faker.pyint(min_value=1)}

        with self.assertRaises(DiscordApiException) as ex:
            discord_api_post(url, data=data)
        ex = ex.exception
        self.assertEqual(500, ex.error_code)
Exemplo n.º 12
0
 def setUp(self):
     self.faker = Faker()
Exemplo n.º 13
0
from faker.proxy import Faker
from model_bakery import baker
from PIL import Image

from bot.commands.roleplay import WorldsCommand
from bot.models import DiscordUser
from bot.utils import get_url_from
from common.constants.models import PLACE_MODEL, USER_MODEL
from common.tools.sync import async_create, async_get
from roleplay.enums import SiteTypes
from tests.bot.helpers import mocks

Place = apps.get_model(PLACE_MODEL)
User = apps.get_model(USER_MODEL)

fake = Faker()


class TestWorldsCommand:
    command = WorldsCommand

    @pytest.fixture(scope='function')
    def user(self):
        user = baker.make(User)
        return user

    @pytest.fixture(scope='function')
    def registered_author(self, user):
        author = mocks.MemberMock()
        discord_user = baker.make(DiscordUser, id=author.id)
        discord_user.user = user
Exemplo n.º 14
0
def get_random_node_list(inventory_size: int = 200) -> Tuple[Dict, Dict, Dict]:
    """Generate a list of random devices

    Args:
        inventory_size (int): Number of nodes in the list. Default 200

    Returns:
        Tuple[Dict, Dict, Dict]: Three dictionaries containing: device info,
            credentials, and a combination of the two dictionaries
    """
    inventory = {}
    credentials = {}
    all_nodes = {}

    fake = Faker()
    Faker.seed(random.randint(1, 10000))

    ports = [22, 443, 1244, 8080, 4565]
    transports = ['ssh', 'https', 'http']
    devtypes = ['panos', 'eos', None]
    namespaces = ['data-center-north', 'south-data-center']
    keys = ['tests/unit/poller/shared/sample_key', None]
    for _ in range(inventory_size):
        entry = {
            'address': fake.ipv4(address_class='c'),
            'username': fake.domain_word(),
            'port': fake.word(ports),
            'transport': fake.word(transports),
            'devtype': fake.word(devtypes),
            'namespace': fake.word(namespaces),
            'jump_host': fake.word([f"// {fake.domain_word()}@{fake.ipv4()}",
                                   None])
        }

        cred = {
            'password': fake.password(),
            'ssh_keyfile': fake.word(keys),
            'jump_host_key_file': fake.word(keys),
            'passphrase': fake.word([fake.password(), None])
        }
        key = f"{entry['namespace']}.{entry['address']}.{entry['port']}"
        inventory[key] = entry
        credentials[key] = cred
        all_nodes[key] = cred.copy()
        all_nodes[key].update(entry)
    return inventory, credentials, all_nodes
Exemplo n.º 15
0
def task_attributes_(faker: Faker) -> Dict[str, str]:
    """Create the basic attributes of a task."""
    return {
        "id_": faker.pyint(),
        "description": faker.sentence(),
    }