Exemplo n.º 1
0
def test_privileged():
    chatcommunicate.parse_room_config("test/test_rooms.yml")

    msg = Fake({
        "owner": {
            "name": "El'endia Starman",
            "id": 1,
            "is_moderator": False
        },
        "room": {
            "_client": {
                "host": "stackexchange.com"
            },
            "id": 11540
        }
    })

    assert chatcommands.amiprivileged(
        original_msg=msg) == "\u2713 You are a privileged user."

    msg.owner.id = 2
    assert chatcommands.amiprivileged(
        original_msg=msg) == "\u2573 " + GlobalVars.not_privileged_warning

    msg.owner.is_moderator = True
    assert chatcommands.amiprivileged(
        original_msg=msg) == "\u2713 You are a privileged user."
Exemplo n.º 2
0
def test_bisect():
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    msg = Fake({
        "owner": {
            "name": "ArtOfCode",
            "id": 121520,
            "is_moderator": True
        },
        "room": {
            "_client": {
                "host": "stackexchange.com"
            },
            "id": 11540
        },
        "content_source": None
    })
    msg.content_source = "!!/bisect :::essayssos.com:::"
    assert chatcommands.bisect(
        None, original_msg=msg
    ) == r"Matched by `essayssos\.com` on [line 1 of watched_keywords.txt](https://github.com/{}/blob/{}/watched_keywords.txt#L1)".format(
        GlobalVars.bot_repo_slug, GlobalVars.commit.id)
    msg.content_source = "!!/bisect OoOasdfghjklOoO"
    assert chatcommands.bisect(
        None, original_msg=msg
    ) == r"'OoOasdfghjklOoO' is not caught by a blacklist or watchlist item."
def test_metasmoke():
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    orig_tell_rooms_with = chatcommunicate.tell_rooms_with
    chatcommunicate.tell_rooms_with = dummy_tell_rooms_with
    msg = Fake({
        "owner": {
            "name": "ArtOfCode",
            "id": 121520,
            "is_moderator": False
        },
        "room": {
            "id": 11540,
            "_client": {
                "host": "stackexchange.com"
            }
        },
        "_client": {
            "host": "stackexchange.com"
        }
    })
    msg_source = "metasmoke is {}. Current failure count: {} " + "({id})".format(
        id=GlobalVars.location)

    chatcommands.metasmoke(original_msg=msg, alias_used="ms-up")
    assert GlobalVars.MSStatus.is_up()
    chatcommands.metasmoke(original_msg=msg, alias_used="ms-down")
    assert GlobalVars.MSStatus.is_down()
    GlobalVars.MSStatus.reset_ms_status()
    assert chatcommands.metasmoke(original_msg=msg,
                                  alias_used="ms-status") == msg_source.format(
                                      "up", 0)
    chatcommunicate.tell_rooms_with = orig_tell_rooms_with
def test_parse_room_config():
    chatcommunicate.parse_room_config("test/test_rooms.yml")

    assert ("stackexchange.com", 11540) in chatcommunicate._command_rooms
    assert ("stackexchange.com", 30332) in chatcommunicate._command_rooms
    assert ("stackoverflow.com", 111347) in chatcommunicate._command_rooms

    assert ("stackexchange.com", 3) not in chatcommunicate._command_rooms
    assert ("stackexchange.com", 54445) not in chatcommunicate._command_rooms
    assert ("meta.stackexchange.com", 89) not in chatcommunicate._command_rooms

    assert ("stackexchange.com", 11540) in chatcommunicate._watcher_rooms
    assert ("stackexchange.com", 3) in chatcommunicate._watcher_rooms
    assert ("meta.stackexchange.com", 89) in chatcommunicate._watcher_rooms

    assert ("stackexchange.com", 30332) not in chatcommunicate._watcher_rooms
    assert ("stackexchange.com", 54445) not in chatcommunicate._watcher_rooms
    assert ("stackoverflow.com", 111347) not in chatcommunicate._watcher_rooms

    assert chatcommunicate._privileges[("stackexchange.com", 11540)] == {1, 16070}
    assert chatcommunicate._privileges[("stackexchange.com", 30332)] == set()
    assert chatcommunicate._privileges[("stackexchange.com", 3)] == set()
    assert chatcommunicate._privileges[("stackexchange.com", 54445)] == set()
    assert chatcommunicate._privileges[("meta.stackexchange.com", 89)] == {42}
    assert chatcommunicate._privileges[("stackoverflow.com", 111347)] == {1337, 256, 4766556}

    assert len(chatcommunicate._room_roles) == 5
    assert chatcommunicate._room_roles["debug"] == {("stackexchange.com", 11540)}
    assert chatcommunicate._room_roles["all"] == {("stackexchange.com", 11540),
                                                  ("stackexchange.com", 54445),
                                                  ("stackoverflow.com", 111347)}
    assert chatcommunicate._room_roles["metatavern"] == {("meta.stackexchange.com", 89)}
    assert chatcommunicate._room_roles["delay"] == {("meta.stackexchange.com", 89)}
    assert chatcommunicate._room_roles["no-all-caps title"] == {("meta.stackexchange.com", 89)}
def test_bisect(command, test_text, expected_result):
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    msg = Fake({
        "owner": {
            "name": "ArtOfCode",
            "id": 121520,
            "is_moderator": True
        },
        "room": {
            "_client": {
                "host": "stackexchange.com"
            },
            "id": 11540
        },
        "content_source": None
    })

    msg.content_source = "!!/{} {}".format(command, test_text)
    print('command:', command)
    print('test_text:', test_text)
    msg.content = msg.content_source
    # All of the substitution references used in the .format() for the expected result are named. Any which are numbers are
    # part of the expected results.
    expected_result = regex.sub(r"(\{\d+(?:,\d+)?\})", r'{\1}',
                                expected_result)
    formatted_expected_result = expected_result.format(
        test_text=test_text,
        bot_repo_slug=GlobalVars.bot_repo_slug,
        commit_id=GlobalVars.commit.id)
    chat_command = getattr(chatcommands, command)
    result = chat_command(None, original_msg=msg)
    print('formatted_expected_result:', formatted_expected_result)
    print('                   result:', result)
    assert result == formatted_expected_result
def test_parse_room_config():
    chatcommunicate.parse_room_config("test/test_rooms.yml")

    assert ("stackexchange.com", 11540) in chatcommunicate._command_rooms
    assert ("stackexchange.com", 30332) in chatcommunicate._command_rooms
    assert ("stackoverflow.com", 111347) in chatcommunicate._command_rooms

    assert ("stackexchange.com", 3) not in chatcommunicate._command_rooms
    assert ("stackexchange.com", 54445) not in chatcommunicate._command_rooms
    assert ("meta.stackexchange.com", 89) not in chatcommunicate._command_rooms

    assert ("stackexchange.com", 11540) in chatcommunicate._watcher_rooms
    assert ("stackexchange.com", 3) in chatcommunicate._watcher_rooms
    assert ("meta.stackexchange.com", 89) in chatcommunicate._watcher_rooms

    assert ("stackexchange.com", 30332) not in chatcommunicate._watcher_rooms
    assert ("stackexchange.com", 54445) not in chatcommunicate._watcher_rooms
    assert ("stackoverflow.com", 111347) not in chatcommunicate._watcher_rooms

    assert chatcommunicate._privileges[("stackexchange.com", 11540)] == {1, 16070}
    assert chatcommunicate._privileges[("stackexchange.com", 30332)] == set()
    assert chatcommunicate._privileges[("stackexchange.com", 3)] == set()
    assert chatcommunicate._privileges[("stackexchange.com", 54445)] == set()
    assert chatcommunicate._privileges[("meta.stackexchange.com", 89)] == {42}
    assert chatcommunicate._privileges[("stackoverflow.com", 111347)] == {1337, 256, 4766556}

    assert len(chatcommunicate._room_roles) == 5
    assert chatcommunicate._room_roles["debug"] == {("stackexchange.com", 11540)}
    assert chatcommunicate._room_roles["all"] == {("stackexchange.com", 11540),
                                                  ("stackexchange.com", 54445),
                                                  ("stackoverflow.com", 111347)}
    assert chatcommunicate._room_roles["metatavern"] == {("meta.stackexchange.com", 89)}
    assert chatcommunicate._room_roles["delay"] == {("meta.stackexchange.com", 89)}
    assert chatcommunicate._room_roles["no-all-caps title"] == {("meta.stackexchange.com", 89)}
Exemplo n.º 7
0
def test_parse_room_config():
    with chatcommunicate._rooms_lock, chatcommunicate._privileges_lock, chatcommunicate._room_roles_lock:
        chatcommunicate.parse_room_config("test/test_rooms.yml")

        assert ("stackexchange.com", 11540) in chatcommunicate._command_rooms
        assert ("stackexchange.com", 30332) in chatcommunicate._command_rooms
        assert ("stackoverflow.com", 111347) in chatcommunicate._command_rooms

        assert ("stackexchange.com", 3) not in chatcommunicate._command_rooms
        assert ("stackexchange.com",
                54445) not in chatcommunicate._command_rooms
        assert ("meta.stackexchange.com",
                89) not in chatcommunicate._command_rooms

        assert ("stackexchange.com", 11540) in chatcommunicate._watcher_rooms
        assert ("stackexchange.com", 3) in chatcommunicate._watcher_rooms
        assert ("meta.stackexchange.com", 89) in chatcommunicate._watcher_rooms

        assert ("stackexchange.com",
                30332) not in chatcommunicate._watcher_rooms
        assert ("stackexchange.com",
                54445) not in chatcommunicate._watcher_rooms
        assert ("stackoverflow.com",
                111347) not in chatcommunicate._watcher_rooms

        assert chatcommunicate._privileges[("stackexchange.com",
                                            11540)] == {121520, 10145}
        assert chatcommunicate._privileges[("stackexchange.com",
                                            30332)] == {121520, 10145}
        assert chatcommunicate._privileges[("stackexchange.com", 3)] == set()
        assert chatcommunicate._privileges[("stackexchange.com",
                                            54445)] == set()
        assert chatcommunicate._privileges[("meta.stackexchange.com",
                                            89)] == {262823}
        assert chatcommunicate._privileges[("stackoverflow.com",
                                            111347)] == {3160466, 603346}

        assert len(chatcommunicate._room_roles) == 5
        assert chatcommunicate._room_roles["debug"] == {("stackexchange.com",
                                                         11540)}
        assert chatcommunicate._room_roles["all"] == {
            ("stackexchange.com", 11540), ("stackexchange.com", 54445),
            ("stackoverflow.com", 111347)
        }
        assert chatcommunicate._room_roles["metatavern"] == {
            ("meta.stackexchange.com", 89)
        }
        assert chatcommunicate._room_roles["delay"] == {
            ("meta.stackexchange.com", 89)
        }
        assert chatcommunicate._room_roles["no-all-caps title"] == {
            ("meta.stackexchange.com", 89)
        }
def test_inqueue():
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    site = Fake({"keys": (lambda: ['1'])})

    class FakeQueue:
        def __getitem__(self, _):
            return site

        def __contains__(self, name):
            return name == "codegolf.stackexchange.com"

    chatcommands.GlobalVars.bodyfetcher = Fake({"queue": FakeQueue()})

    assert chatcommands.inqueue(
        "https://codegolf.stackexchange.com/a/1") == "Can't check for answers."
    assert chatcommands.inqueue(
        "https://stackoverflow.com/q/1") == "Not in queue."
    assert chatcommands.inqueue(
        "https://codegolf.stackexchange.com/q/1") == "#1 in queue."
def test_bisect():
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    msg = Fake({
        "owner": {
            "name": "ArtOfCode",
            "id": 121520,
            "is_moderator": True
        },
        "room": {
            "_client": {
                "host": "stackexchange.com"
            },
            "id": 11540
        },
        "content_source": None
    })
    msg.content_source = "!!/bisect :::essayssos.com:::"
    assert chatcommands.bisect(None, original_msg=msg) == r"Matched by `essayssos\.com` on [line 1 of watched_keywords.txt](https://github.com/Charcoal-SE/SmokeDetector/blob/{}/watched_keywords.txt#L1)".format(GlobalVars.commit.id)
    msg.content_source = "!!/bisect OoOasdfghjklOoO"
    assert chatcommands.bisect(None, original_msg=msg) == r"'OoOasdfghjklOoO' is not caught by a blacklist or watchlist item."
def test_reject(monkeypatch):
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    msg = Fake({
        "_client": {
            "host": "stackexchange.com",
        },
        "id": 88888888,
        "owner": {
            "name": "ArtOfCode",
            "id": 121520
        },
        "room": {
            "id": 11540,
            "name": "Continuous Integration",
            "_client": None
        },
        "content_source": '!!/reject 8888',
    })
    msg.room._client = msg._client

    # Prevent from attempting to check privileges with Metasmoke
    monkeypatch.setattr(GlobalVars, "code_privileged_users", [])
    assert chatcommands.reject('8888 "test"',
                               original_msg=msg,
                               alias_used="reject").startswith(
                                   "You need blacklist manager privileges")

    monkeypatch.setattr(GlobalVars, "code_privileged_users",
                        [('stackexchange.com', 121520)])
    with monkeypatch.context() as m:
        # Oh no GitHub is down
        original_get = requests.get
        m.setattr("requests.get", lambda *args, **kwargs: None)
        assert chatcommands.reject(
            '8888 "test"', original_msg=msg,
            alias_used="reject-force") == "Cannot connect to GitHub API"
        m.setattr("requests.get", original_get)
    assert chatcommands.reject('2518 "test"',
                               original_msg=msg,
                               alias_used="close").startswith("Please provide")
Exemplo n.º 11
0
def test_privileged():
    chatcommunicate.parse_room_config("test/test_rooms.yml")

    msg = Fake({
        "owner": {
            "name": "ArtOfCode",
            "id": 121520,
            "is_moderator": False
        },
        "room": {
            "_client": {
                "host": "stackexchange.com"
            },
            "id": 11540
        }
    })

    assert chatcommands.amiprivileged(original_msg=msg) == "\u2713 You are a privileged user."

    msg.owner.id = 2
    assert chatcommands.amiprivileged(original_msg=msg) == "\u2573 " + GlobalVars.not_privileged_warning

    msg.owner.is_moderator = True
    assert chatcommands.amiprivileged(original_msg=msg) == "\u2713 You are a privileged user."
def test_allspam(handle_spam):
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    try:
        msg = Fake({
            "owner": {
                "name": "ArtOfCode",
                "id": 121520,
                "is_moderator": False
            },
            "room": {
                "id": 11540,
                "name": "Charcoal HQ",
                "_client": {
                    "host": "stackexchange.com"
                }
            },
            "_client": {
                "host": "stackexchange.com"
            },
            "id": 1337
        })

        assert chatcommands.allspam(
            "test",
            original_msg=msg) == "That doesn't look like a valid user URL."

        # If this code lasts long enough to fail, I'll be happy
        assert chatcommands.allspam("https://stackexchange.com/users/10000000000", original_msg=msg) == \
            "The specified user does not appear to exist."

        assert chatcommands.allspam(
            "https://stackexchange.com/users/5869449", original_msg=msg
        ) == (
            "The specified user has an abnormally high number of accounts. Please consider flagging for moderator "
            "attention, otherwise use !!/report on the user's posts individually."
        )

        assert chatcommands.allspam(
            "https://stackexchange.com/users/11683", original_msg=msg
        ) == (
            "The specified user's reputation is abnormally high. Please consider flagging for moderator attention, "
            "otherwise use !!/report on the posts individually.")

        assert chatcommands.allspam(
            "https://stackoverflow.com/users/22656", original_msg=msg
        ) == (
            "The specified user's reputation is abnormally high. Please consider flagging for moderator attention, "
            "otherwise use !!/report on the posts individually.")

        assert chatcommands.allspam("https://stackexchange.com/users/12108751", original_msg=msg) == \
            "The specified user hasn't posted anything."

        assert chatcommands.allspam("https://stackoverflow.com/users/8846458", original_msg=msg) == \
            "The specified user has no posts on this site."

        # This test is for users with <100rep but >15 posts
        # If this breaks in the future because the below user eventually gets 100 rep (highly unlikely), use the following
        # data.SE query to find a new target. Alternatively, get a sock to post 16 answers in the sandbox.
        # https://stackoverflow.com/users/7052649/vibin (look for low rep but >1rep users, 1rep users are usually suspended)
        assert chatcommands.allspam(
            "https://stackoverflow.com/users/7052649", original_msg=msg
        ) == (
            "The specified user has an abnormally high number of spam posts. Please consider flagging for moderator "
            "attention, otherwise use !!/report on the posts individually.")

        # Valid user for allspam command
        assert chatcommands.allspam("https://stackexchange.com/users/12108974",
                                    original_msg=msg) is None

        assert handle_spam.call_count == 1
        _, call = handle_spam.call_args_list[0]
        assert isinstance(call["post"], Post)
        assert call["reasons"] == ["Manually reported answer"]
        assert call[
            "why"] == "User manually reported by *ArtOfCode* in room *Charcoal HQ*.\n"

        handle_spam.reset_mock()
        assert chatcommands.allspam(
            "https://meta.stackexchange.com/users/373807",
            original_msg=msg) is None

        assert handle_spam.call_count == 1
        _, call = handle_spam.call_args_list[0]
        assert isinstance(call["post"], Post)
        assert call["reasons"] == ["Manually reported answer"]
        assert call[
            "why"] == "User manually reported by *ArtOfCode* in room *Charcoal HQ*.\n"

    finally:
        GlobalVars.blacklisted_users.clear()
def test_notifications():
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    try:
        msg1 = Fake({
            "owner": {
                "name": "El'endia Starman",
                "id": 1,
                "is_moderator": False
            },
            "room": {
                "id": 11540,
                "_client": {
                    "host": "stackexchange.com"
                }
            },
            "_client": {
                "host": "stackexchange.com"
            }
        })

        msg2 = Fake({
            "owner": {
                "name": "angussidney",
                "id": 145827,
                "is_moderator": False
            },
            "room": {
                "id": 11540,
                "_client": {
                    "host": "stackexchange.com"
                }
            },
            "_client": {
                "host": "stackexchange.com"
            }
        })

        # User 1
        assert chatcommands.allnotificationsites("11540", original_msg=msg1) == \
            "You won't get notified for any sites in that room."
        assert chatcommands.willbenotified("11540", "gaming", original_msg=msg1) == \
            "No, you won't be notified for that site in that room."
        assert chatcommands.notify("11540", "gaming", None, original_msg=msg1) == \
            "You'll now get pings from me if I report a post on `gaming`, in room `11540` on `chat.stackexchange.com`."
        assert chatcommands.notify("11540", "codegolf.stackexchange.com", None, original_msg=msg1) == \
            "You'll now get pings from me if I report a post on `codegolf.stackexchange.com`, in room `11540` on " \
            "`chat.stackexchange.com`."
        # Check for additional text when notifying only when in room
        assert chatcommands.notify("11540", "meta.stackexchange.com", False, original_msg=msg1) == \
            "You'll now get pings from me if I report a post on `meta.stackexchange.com`, in room `11540` on " \
            "`chat.stackexchange.com`, but only when you're in that room."
        # Remove notification which is active only when in room
        assert chatcommands.unnotify("11540", "meta.stackexchange.com", original_msg=msg1) == \
            "I will no longer ping you if I report a post on `meta.stackexchange.com`, in room `11540` on " \
            "`chat.stackexchange.com`."
        assert chatcommands.willbenotified("11540", "gaming.stackexchange.com", original_msg=msg1) == \
            "Yes, you will be notified for that site in that room."
        assert chatcommands.willbenotified("11540", "codegolf", original_msg=msg1) == \
            "Yes, you will be notified for that site in that room."

        # User 2
        assert chatcommands.allnotificationsites("11540", original_msg=msg2) == \
            "You won't get notified for any sites in that room."
        assert chatcommands.willbenotified("11540", "raspberrypi", original_msg=msg2) == \
            "No, you won't be notified for that site in that room."
        assert chatcommands.notify("11540", "raspberrypi", None, original_msg=msg2) == \
            "You'll now get pings from me if I report a post on `raspberrypi`, in room `11540` on `chat.stackexchange.com`."
        assert chatcommands.notify("11540", "raspberrypi", None, original_msg=msg2) == \
            "That notification configuration is already registered."
        assert chatcommands.willbenotified("11540", "raspberrypi.stackexchange.com", original_msg=msg2) == \
            "Yes, you will be notified for that site in that room."

        # Check for no interaction
        assert chatcommands.allnotificationsites("11540", original_msg=msg1) == \
            "You will get notified for these sites:\r\ncodegolf.stackexchange.com, gaming.stackexchange.com"
        assert chatcommands.allnotificationsites("11540", original_msg=msg2) == \
            "You will get notified for these sites:\r\nraspberrypi.stackexchange.com"

        # Remove all notifications and check
        assert chatcommands.unnotify("11540", "gaming.stackexchange.com", original_msg=msg1) == \
            "I will no longer ping you if I report a post on `gaming.stackexchange.com`, in room `11540` on " \
            "`chat.stackexchange.com`."
        assert chatcommands.unnotify("11540", "codegolf", original_msg=msg1) == \
            "I will no longer ping you if I report a post on `codegolf`, in room `11540` on `chat.stackexchange.com`."
        assert chatcommands.unnotify("11540", "raspberrypi", original_msg=msg2) == \
            "I will no longer ping you if I report a post on `raspberrypi`, in room `11540` on `chat.stackexchange.com`."
        assert chatcommands.unnotify("11540", "raspberrypi", original_msg=msg2) == \
            "That configuration doesn't exist."
        assert chatcommands.allnotificationsites("11540", original_msg=msg1) == \
            "You won't get notified for any sites in that room."
        assert chatcommands.willbenotified("11540", "raspberrypi", original_msg=msg2) == \
            "No, you won't be notified for that site in that room."

        assert chatcommands.allnotificationsites(
            "asdf",
            original_msg=msg1) == "Invalid input type given for an argument"
        assert chatcommands.notify("11540", "charcoalspam.stackexchange.com", None, original_msg=msg1) == \
            "The given SE site does not exist."

        assert chatcommands.notify("11540", "codegolf", "True", original_msg=msg1) == \
            "You'll now get pings from me if I report a post on `codegolf`, in room `11540` on `chat.stackexchange.com`."
        assert chatcommands.notify("11540", "codegolf", "False", original_msg=msg1) == \
            "That notification configuration is already registered."
    finally:
        # Cleanup
        remove_pickle("notifications.p")
def test_whitelisted_users():
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    try:
        msg = Fake({
            "owner": {
                "name": "El'endia Starman",
                "id": 1,
                "is_moderator": False
            },
            "room": {
                "id": 11540,
                "_client": {
                    "host": "stackexchange.com"
                }
            },
            "_client": {
                "host": "stackexchange.com"
            }
        })

        # Format: !!/*wlu profileurl
        assert chatcommands.iswlu("https://stackoverflow.com/users/4622463/angussidney", original_msg=msg) == \
            "User is not whitelisted (`4622463` on `stackoverflow.com`)."
        assert chatcommands.addwlu("https://stackoverflow.com/users/4622463/angussidney", original_msg=msg) == \
            "User whitelisted (`4622463` on `stackoverflow.com`)."
        # TODO: Add test here as well
        assert chatcommands.iswlu("https://stackoverflow.com/users/4622463/angussidney", original_msg=msg) == \
            "User is whitelisted (`4622463` on `stackoverflow.com`)."
        assert chatcommands.rmwlu("https://stackoverflow.com/users/4622463/angussidney", original_msg=msg) == \
            "User removed from whitelist (`4622463` on `stackoverflow.com`)."
        assert chatcommands.iswlu("https://stackoverflow.com/users/4622463/angussidney", original_msg=msg) == \
            "User is not whitelisted (`4622463` on `stackoverflow.com`)."
        assert chatcommands.rmwlu("https://stackoverflow.com/users/4622463/angussidney", original_msg=msg) == \
            "User is not whitelisted."

        # Format: !!/*wlu userid sitename
        assert chatcommands.iswlu("4622463 stackoverflow", original_msg=msg) == \
            "User is not whitelisted (`4622463` on `stackoverflow.com`)."
        assert chatcommands.addwlu("4622463 stackoverflow", original_msg=msg) == \
            "User whitelisted (`4622463` on `stackoverflow.com`)."
        # TODO: Add test here as well
        assert chatcommands.iswlu("4622463 stackoverflow", original_msg=msg) == \
            "User is whitelisted (`4622463` on `stackoverflow.com`)."
        assert chatcommands.rmwlu("4622463 stackoverflow", original_msg=msg) == \
            "User removed from whitelist (`4622463` on `stackoverflow.com`)."
        assert chatcommands.iswlu("4622463 stackoverflow", original_msg=msg) == \
            "User is not whitelisted (`4622463` on `stackoverflow.com`)."
        assert chatcommands.rmwlu("4622463 stackoverflow", original_msg=msg) == \
            "User is not whitelisted."

        # Invalid input
        assert chatcommands.addwlu("https://meta.stackexchange.com/users", original_msg=msg) == \
            "Invalid format. Valid format: `!!/addwlu profileurl` *or* `!!/addwlu userid sitename`."
        assert chatcommands.rmwlu("https://meta.stackexchange.com/", original_msg=msg) == \
            "Invalid format. Valid format: `!!/rmwlu profileurl` *or* `!!/rmwlu userid sitename`."
        assert chatcommands.iswlu("msklkldsklaskd", original_msg=msg) == \
            "Invalid format. Valid format: `!!/iswlu profileurl` *or* `!!/iswlu userid sitename`."

        # Invalid sitename
        assert chatcommands.addwlu("1 completelyfakesite", original_msg=msg) == \
            "Error: Could not find the given site."
        assert chatcommands.iswlu("1 completelyfakesite", original_msg=msg) == \
            "Error: Could not find the given site."
    except:
        # Cleanup
        remove_pickle("whitelistedUsers.p")
def test_report(handle_spam):
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    # Documentation: The process before scanning the post is identical regardless of alias_used.
    #   No need to supply alias_used to test that part.
    #   If no alias_used is supplied, it acts as if it's "scan"
    try:
        msg = Fake({
            "owner": {
                "name": "ArtOfCode",
                "id": 121520,
                "is_moderator": False
            },
            "room": {
                "id": 11540,
                "name": "Charcoal HQ",
                "_client": {
                    "host": "stackexchange.com"
                }
            },
            "_client": {
                "host": "stackexchange.com"
            },
            "id": 1337
        })

        assert chatcommands.report(
            "test", original_msg=msg, alias_used="report"
        ) == "Post 1: That does not look like a valid post URL."

        assert chatcommands.report(
            "one two three four five plus-an-extra",
            original_msg=msg,
            alias_used="report"
        ) == (
            "To avoid SmokeDetector reporting posts too slowly, you can report at most 5 posts at a time. This is to avoid "
            "SmokeDetector's chat messages getting rate-limited too much, which would slow down reports."
        )

        # assert chatcommands.report('a a a a a "invalid"""', original_msg=msg) \
        #     .startswith("You cannot provide multiple custom report reasons.")

        assert chatcommands.report('https://stackoverflow.com/q/1', original_msg=msg) == \
            "Post 1: Could not find data for this post in the API. It may already have been deleted."

        # Valid post
        assert chatcommands.report('https://stackoverflow.com/a/1732454', original_msg=msg, alias_used="scan") == \
            "Post 1: This does not look like spam"
        assert chatcommands.report(
            'https://stackoverflow.com/a/1732454 "~o.O~"',
            original_msg=msg,
            alias_used="report") is None

        _, call = handle_spam.call_args_list[-1]
        assert isinstance(call["post"], Post)
        assert call["reasons"] == ["Manually reported answer"]
        assert call["why"] == (
            "Post manually reported by user *ArtOfCode* in room *Charcoal HQ* with reason: *~o.O~*."
            "\n\nThis post would not have been caught otherwise.")

        # Bad post
        # This post is found in Sandbox Archive, so it will remain intact and is a reliable test post
        # backup: https://meta.stackexchange.com/a/228635
        test_post_url = "https://meta.stackexchange.com/a/209772"
        assert chatcommands.report(
            test_post_url, original_msg=msg, alias_used="scan") is None

        _, call = handle_spam.call_args_list[-1]
        assert isinstance(call["post"], Post)
        assert call["why"].startswith(
            "Post manually scanned by user *ArtOfCode* in room *Charcoal HQ*.")

        # Now with report-direct
        GlobalVars.blacklisted_users.clear()
        GlobalVars.latest_questions.clear()
        assert chatcommands.report(test_post_url,
                                   original_msg=msg,
                                   alias_used="report-direct") is None
        _, call = handle_spam.call_args_list[-1]
        assert isinstance(call["post"], Post)
        assert call["why"].startswith(
            "Post manually reported by user *ArtOfCode* in room *Charcoal HQ*."
            "\n\nThis post would have also been caught for:")

        # Don't re-report
        GlobalVars.latest_questions = [
            ('stackoverflow.com', '1732454',
             'RegEx match open tags except XHTML self-contained tags')
        ]
        assert chatcommands.report(
            'https://stackoverflow.com/a/1732454',
            original_msg=msg).startswith("Post 1: Already recently reported")

        # Can use report command multiple times in 30s if only one URL was used
        assert chatcommands.report('https://stackoverflow.com/q/1732348',
                                   original_msg=msg,
                                   alias_used="report") is None
    finally:
        GlobalVars.blacklisted_users.clear()
        GlobalVars.latest_questions.clear()
def test_watch(monkeypatch):
    chatcommunicate.parse_room_config("test/test_rooms.yml")

    # XXX TODO: expand

    def wrap_watch(pattern, force=False):
        cmd = 'watch{0}'.format('-force' if force else '')
        msg = Fake({
            "_client": {
                "host": "stackexchange.com",
                "get_user": lambda id: Fake({
                    "name": "J F",
                    "id": id
                })
            },
            "owner": {
                "name": "ArtOfCode",
                "id": 121520
            },
            "room": {
                "id": 11540,
                "get_current_user_ids": lambda: [161943]
            },
            # Ouch, this is iffy
            # Prevent an error from deep inside do_blacklist
            "content_source": '!!/{0} {1}'.format(cmd, pattern)
        })
        msg.content = msg.content_source
        msg.room._client = msg._client

        return chatcommands.watch(pattern, alias_used=cmd, original_msg=msg)

    # Prevent from attempting to check privileges with Metasmoke
    monkeypatch.setattr(GlobalVars, "code_privileged_users", [1, 161943])

    try:
        # Invalid regex
        resp = wrap_watch(r'?')
        assert "An invalid pattern was provided" in resp

        # This is one of the perpetually condemned spam domains, blacklisted forever
        resp = wrap_watch(r'israelbigmarket')
        assert "That pattern looks like it's already caught" in resp

        # The phone number here is the first one which used to be in this format in bad_keywords.txt.
        # It is now in blacklisted_numbers.txt.
        resp = wrap_watch(r'[a-z_]*(?:1_*)?913[\W_]*608[\W_]*4584[a-z_]*')
        assert "Mostly non-latin" not in resp
        assert "Bad phone number in answer" in resp
        assert "Bad phone number in body" in resp

        # XXX TODO: figure out how to trigger duplicate entry separately
        monkeypatch.setattr("chatcommunicate.is_privileged",
                            lambda *args: True)
        monkeypatch.setattr("gitmanager.GitManager.prepare_git_for_operation",
                            lambda *args: (True, None))

        assert wrap_watch("trimfire", True).startswith("Already watched")

        monkeypatch.setattr("gitmanager.GitManager.add_to_blacklist",
                            lambda *args, **kwargs: (True, "Hahaha"))
        assert wrap_watch("male enhancement", True) == "Hahaha"
    finally:
        git.checkout("master")
def test_deprecated_blacklist():
    chatcommunicate.parse_room_config("test/test_rooms.yml")
    assert chatcommands.blacklist("").startswith(
        "The `!!/blacklist` command has been deprecated.")
Exemplo n.º 18
0
 def wrap(*args, **kwargs):
     chatcommunicate.parse_room_config("test/test_rooms.yml")
     return func(*args, **kwargs)