import datetime import pytest from fbchat import ParseError from fbchat._session import ( parse_server_js_define, base36encode, prefix_url, generate_message_id, session_factory, client_id_factory, find_form_request, get_error_data, ) def test_parse_server_js_define(): html = """ some data;require("TimeSliceImpl").guard(function(){(require("ServerJSDefine")).handleDefines([["DTSGInitialData",[],{"token":"123"},100]]) other irrelevant data """ define = parse_server_js_define(html) assert define == { "DTSGInitialData": {"token": "123"}, "DTSGInitData": {"async_get_token": "12345", "token": "123"}, } def test_parse_server_js_define_error(): with pytest.raises(ParseError, match="Could not find any"): parse_server_js_define("") html = 'function(){(require("ServerJSDefine")).handleDefines([{"a": function(){}}])' with pytest.raises(ParseError, match="Invalid"): parse_server_js_define(html + html) html = 'function(){require("ServerJSDefine").handleDefines({"a": "b"})' with pytest.raises(ParseError, match="Invalid"): parse_server_js_define(html + html) @pytest.mark.parametrize( "number,expected", [(1, "1"), (10, "a"), (123, "3f"), (1000, "rs"), (123456789, "21i3v9")], ) def test_base36encode(number, expected): assert base36encode(number) == expected def test_prefix_url(): static_url = "https://upload.messenger.com/" assert prefix_url(static_url) == static_url assert prefix_url("/") == "https://www.messenger.com/" assert prefix_url("/abc") == "https://www.messenger.com/abc" def test_generate_message_id(): # Returns random output, so hard to test more thoroughly assert generate_message_id(datetime.datetime.utcnow(), "def") def test_session_factory(): session = session_factory() assert session.headers def test_client_id_factory(): # Returns random output, so hard to test more thoroughly assert client_id_factory() def test_find_form_request(): html = """
Two factor authentication required
You've asked us to require a 6-digit login code when anyone tries to access your account from a new device or browser.
Enter the 6-digit code from your Code Generator or 3rd party app below.
""" url, data = find_form_request(html) assert url.startswith("https://www.facebook.com/checkpoint/") assert { "jazoest": "some-number", "fb_dtsg": "some-base64", "nh": "some-hex", "no_fido": "true", "approvals_code": "[missing]", "submit[Continue]": "Continue", } == data def test_find_form_request_error(): with pytest.raises(ParseError, match="Could not find form to submit"): assert find_form_request("") with pytest.raises(ParseError, match="Could not find url to submit to"): assert find_form_request("
") def test_get_error_data(): html = """ Messenger
Type your password again
The password you entered is incorrect. Did you forget your password?
""" msg = "The password you entered is incorrect. Did you forget your password?" assert msg == get_error_data(html)