Esempio n. 1
0
 def test_collect(self):
     user = User()
     post = Post()
     db.session.add(user)
     db.session.commit()
     user.collect(post)
     assert user.is_collecting(post)
Esempio n. 2
0
    def test_edit_profile(self):

        user = User(name="abcd",
                    username="******",
                    email="*****@*****.**",
                    confirmed=True)
        user.set_password("123456")
        db.session.add(user)
        db.session.commit()
        self.login(username="******", password="******")
        response = self.client.get("/profile/edit/")
        response_data = response.get_data(as_text=True)
        assert "abcd" in response_data

        data = {
            "username": "******",
            "name": fake.name(),
            "location": fake.address(),
            "about_me": fake.sentence(),
            "custom_avatar_url": "https://example.com/test.png",
        }
        response = self.client.post("/profile/edit/",
                                    data=data,
                                    follow_redirects=True)
        assert response.status_code == 200
        user = User.query.filter_by(username="******").first()
        assert user.name == data["name"]
        assert user.location == data["location"]
        assert user.about_me == data["about_me"]
        assert user.custom_avatar_url == data["custom_avatar_url"]
        self.logout()
Esempio n. 3
0
    def test_group(self):

        u2 = User(username="******", email="*****@*****.**")
        u2.set_password("123456")
        db.session.add(u2)
        db.session.commit()

        # test create group with private
        g_dict = dict(name="test-group", private=True)
        response = self.client.post("/api/v3/group/create",
                                    json=g_dict,
                                    headers=self.get_api_v3_headers())
        assert response.status_code == 200
        g = Group.query.filter_by(name="test-group").first()

        response = self.client.get(f"/api/v3/group/{g.id}",
                                   headers=self.get_api_v3_headers(
                                       "u2", "123456"))
        assert response.status_code == 403

        # test create group with members
        g_dict = dict(name="test-group2", members=[u2.id])
        response = self.client.post("/api/v3/group/create",
                                    json=g_dict,
                                    headers=self.get_api_v3_headers())
        assert response.status_code == 200
        g = Group.query.filter_by(name="test-group2").first()

        response = self.client.get(f"/api/v3/group/{g.id}",
                                   headers=self.get_api_v3_headers(
                                       "u2", "123456"))
        assert response.status_code == 200

        # test PUT group
        modified = dict(members=[u2.id])
        response = self.client.put(f"/api/v3/group/{g.id}",
                                   headers=self.get_api_v3_headers(),
                                   json=modified)
        assert response.status_code == 200
        data = response.get_json()

        assert any(u2.id == u["id"] for u in data["members"])

        # test GET /self/groups
        response = self.client.get(f"/api/v3/self/groups",
                                   headers=self.get_api_v3_headers(
                                       "u2", "123456"))
        assert response.status_code == 200
        assert any(g["name"] == "test-group2" for g in response.get_json())

        # test DELETE group
        response = self.client.delete(f"/api/v3/group/{g.id}",
                                      headers=self.get_api_v3_headers())
        assert response.status_code == 204
Esempio n. 4
0
def verify_token(token: str):
    user = User.verify_auth_token_api(token)
    if user:
        g.current_user = user
        user.ping()
        return user
    return None
Esempio n. 5
0
def validate_token(token):
    user = User.verify_auth_token_api(token)
    if user is None:
        return False
    g.current_user = user
    user.ping()
    return True
Esempio n. 6
0
 def test_level(self):
     experience_level_table = {
         0: (1, "eee"),
         100: (2, "ff9"),
         200: (3, "afa"),
         350: (4, "5d5"),
         550: (5, "0dd"),
         800: (6, "00f"),
         1100: (7, "da3"),
         1500: (8, "f00"),
     }
     u = User()
     for k, v in experience_level_table.items():
         u.experience = k
         assert u.level() == v[0]
         assert (u.level_badge_link() == "https://img.shields.io/badge/Lv" +
                 str(v[0]) + "%20-" + v[1])
Esempio n. 7
0
    def test_coins(self):
        u = User()
        u.last_seen = datetime(2021, 8, 13, 23, 59, 59)
        force_time = datetime(2021, 8, 14, 23, 59, 59)
        u.ping(force_time)
        assert u.coins == 4

        u.last_seen = datetime(2021, 8, 14)
        u.ping(force_time)
        assert u.coins == 4
Esempio n. 8
0
 def test_lv9(self):
     u = User()
     u.experience = 2700
     assert u.level() == 10
     u.experience = 3100
     assert u.level() == 11
     assert u.level_badge_link().endswith("%20%2B2-808")
Esempio n. 9
0
 def test_delete_column(self):
     user = User()
     column = Column()
     db.session.add(column)
     db.session.commit()
     user.columns.append(column)
     assert column in user.columns
     column.delete()
     assert column not in user.columns
Esempio n. 10
0
File: views.py Progetto: z-t-y/Flog
 def post(self, data):
     """Verify an input token"""
     user = User.verify_auth_token_api(data["token"])
     if user is None:
         abort(401)
     schema = VerifyTokenOutSchema()
     schema.valid = True
     schema.username = user.username
     return schema
Esempio n. 11
0
 def test_column(self):
     user = User()
     post = Post()
     column = Column()
     column.posts.append(post)
     db.session.add(column)
     db.session.commit()
     assert post in column.posts
     user.columns.append(column)
     assert column in user.columns
     assert post in user.posts
Esempio n. 12
0
 def commonSetUp(self):
     warnings.simplefilter("ignore")
     self.context = self.app.test_request_context()
     self.client = self.app.test_client()
     self.context.push()
     if not os.path.exists(self.app.config["UPLOAD_DIRECTORY"]):
         os.mkdir(self.app.config["UPLOAD_DIRECTORY"])
     db.drop_all()
     db.create_all()
     self.admin = User(
         name=self.app.config["FLOG_ADMIN"],
         username=self.app.config["FLOG_ADMIN"],
         email=self.app.config["FLOG_ADMIN_EMAIL"],
         confirmed=True,
     )
     self.admin.set_password(self.app.config["FLOG_ADMIN_PASSWORD"])
     self.admin.is_admin = True
     db.session.add(self.admin)
     db.session.commit()
     fakes.users(5)
     fakes.posts(5)
     fakes.comments(5)
Esempio n. 13
0
def verify_password_or_token(username_or_token, password):

    if username_or_token == "":
        return False
    if password == "":
        g.current_user = User.verify_auth_token_api(username_or_token)
        return g.current_user is not None
    user = User.query.filter_by(username=username_or_token).first()
    if not user:
        return False
    g.current_user = user
    g.current_user.ping()
    return user.verify_password(password)
Esempio n. 14
0
File: views.py Progetto: z-t-y/Flog
 def post(self, data):
     """Register a new user"""
     user = User()
     for attr, value in data.items():
         if attr == "password":
             user.set_password(value)
         user.__setattr__(attr, value)
     db.session.add(user)
     db.session.commit()
     return user
Esempio n. 15
0
class Base(unittest.TestCase):
    app = None

    def commonSetUp(self):
        warnings.simplefilter("ignore")
        self.context = self.app.test_request_context()
        self.client = self.app.test_client()
        self.context.push()
        if not os.path.exists(self.app.config["UPLOAD_DIRECTORY"]):
            os.mkdir(self.app.config["UPLOAD_DIRECTORY"])
        db.drop_all()
        db.create_all()
        self.admin = User(
            name=self.app.config["FLOG_ADMIN"],
            username=self.app.config["FLOG_ADMIN"],
            email=self.app.config["FLOG_ADMIN_EMAIL"],
            confirmed=True,
        )
        self.admin.set_password(self.app.config["FLOG_ADMIN_PASSWORD"])
        self.admin.is_admin = True
        db.session.add(self.admin)
        db.session.commit()
        fakes.users(5)
        fakes.posts(5)
        fakes.comments(5)

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        filename = self.app.config["FLOG_ADMIN"] + "_" + "test.png"
        test_image_path = os.path.join(self.app.config["UPLOAD_DIRECTORY"], filename)
        test_image_path2 = os.path.join(
            self.app.config["UPLOAD_DIRECTORY"], "test_test.png"
        )
        try:
            if os.path.exists(test_image_path):
                os.remove(test_image_path)
            if os.path.exists(test_image_path2):
                os.remove(test_image_path2)
        except:
            pass
        self.context.pop()

    def login(
        self,
        username=os.getenv("FLOG_ADMIN"),
        password=os.getenv("FLOG_ADMIN_PASSWORD"),
    ):
        """Login helper function"""
        if username is None:
            username = self.app.config["FLOG_ADMIN"]
        if password is None:
            password = self.app.config["FLOG_ADMIN_PASSWORD"]
        return self.client.post(
            "/auth/login/",
            data=dict(username_or_email=username, password=password),
            follow_redirects=True,
        )

    def logout(self):
        """Logout helper function"""
        return self.client.get("/auth/logout/", follow_redirects=True)

    def register(
        self,
        name: str = "Test",
        username: str = "test",
        password: str = "password",
        email: str = "*****@*****.**",
    ):
        """Register helper function"""
        return self.client.post(
            "/auth/register/",
            data=dict(
                name=name,
                username=username,
                email=email,
                password=password,
                password_again=password,
            ),
            follow_redirects=True,
        )

    def generate_post(
        self, title=fake.sentence(), text=fake.text(), private=False, **kwargs
    ) -> dict:
        """Create a post for test use"""
        if kwargs.get("login") is True:
            self.login(**kwargs)
        data = dict(
            title=title, content=f"<p>{text}</p>", private=private if private else None
        )

        return {
            "response": self.client.post("/write/", data=data, follow_redirects=True),
            "post": data,
            "text": text,
            "title": title,
        }

    def generate_column(self, name=fake.word(), columns=None) -> dict:
        if columns is None:
            columns = []
        data = dict(
            name=name,
            columns=columns,
        )
        response = self.client.post("/column/create/", data=data, follow_redirects=True)
        return dict(response=response, column_name=name)

    def send_notification(self) -> None:
        """Send notifications for test user"""
        self.login()
        admin = User.query.filter_by(is_admin=True).first()
        notification = Notification(message="test", receiver=admin)
        db.session.add(notification)
        db.session.commit()

    def get_api_v1_headers(
        self, username: str = "test", password: str = "password", **kwargs
    ) -> dict:
        """Returns auth headers for api v1"""
        if kwargs.get("content_type"):
            content_type = kwargs["content_type"]
        else:
            content_type = "application/json"
        return {
            "Authorization": "Basic "
            + b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8"),
            "Accept": "application/json",
            "Content-Type": content_type,
        }

    def get_api_v2_headers(
        self,
        username: str = "test",
        password: str = "password",
        custom_token: str = None,
        **kwargs,
    ) -> dict:
        """Returns auth headers for api v2"""
        response = self.client.post(
            "/api/v2/oauth/token/",
            data=dict(grant_type="password", username=username, password=password),
        )
        return self.get_token_from_response(response, custom_token, **kwargs)

    def get_api_v3_headers(
        self,
        username: str = "test",
        password: str = "password",
        custom_token: str = None,
        **kwargs,
    ) -> dict:
        """Returns auth headers for api v3"""
        response = self.client.post(
            "/api/v3/token",
            data=dict(username=username, password=password),
        )
        return self.get_token_from_response(response, custom_token, **kwargs)

    @staticmethod
    def get_token_from_response(response, custom_token: str, **kwargs):
        data = response.get_json()
        token = "Bearer " + str(data.get("access_token"))
        if custom_token is not None:
            token = custom_token
        if kwargs.get("content_type"):
            content_type = kwargs["content_type"]
        else:
            content_type = "application/json"
        return {
            "Authorization": token,
            "Accept": "application/json",
            "Content-Type": content_type,
        }

    def get_response_and_data_of_post(self, post_id: int) -> tuple:
        response = self.client.get(f"/post/{post_id}", follow_redirects=True)
        data = response.get_data(as_text=True)
        return response, data

    def upload_image(self):
        os.chdir(os.path.dirname(__file__))
        image_obj = open("test.png", "rb")
        data = {"upload": image_obj}
        os.chdir(os.path.dirname(os.path.dirname(__file__)))
        return self.client.post("/image/upload/", data=data, follow_redirects=True)

    def delete_image(self, image_id: int):
        return self.client.post(f"/image/delete/{image_id}/", follow_redirects=True)

    def api_upload_image(self, api_bp_prefix: str, headers: dict) -> dict:
        os.chdir(os.path.dirname(__file__))
        image_obj = open("test.png", "rb")
        os.chdir(os.path.dirname(os.path.dirname(__file__)))
        response = self.client.post(
            f"{api_bp_prefix}/image/upload",
            headers=headers,
            data=dict(upload=image_obj),
            follow_redirects=True,
        )
        return {
            "response": response,
            "data": response.get_json(),
        }
Esempio n. 16
0
 def test_avatar_url(self):
     user = User(email="*****@*****.**")
     user.custom_avatar_url = "https://example.com/test.png"
     assert user.avatar_url() == "https://example.com/test.png"
Esempio n. 17
0
 def test_group(self):
     user = User()
     group = Group()
     user.join_group(group)
     assert user.in_group(group)
Esempio n. 18
0
 def test_confirmation_token(self):
     u = User(email="*****@*****.**")
     token = u.generate_confirmation_token()
     assert u.confirm(token)
Esempio n. 19
0
 def test_password_salts_are_random(self):
     u1 = User()
     u2 = User()
     u1.set_password("hello")
     u2.set_password("hello")
     assert u1.password_hash != u2.password_hash
Esempio n. 20
0
 def test_password_verification(self):
     u = User()
     u.set_password("hello")
     assert u.verify_password("hello")
     assert not u.verify_password("bye")
Esempio n. 21
0
 def test_block_user(self):
     user = User()
     user.lock()
     assert user.locked
     user.unlock()
     assert not user.locked
Esempio n. 22
0
 def test_notification(self):
     user = User()
     notification = Notification(message="Hello World", receiver=user)
     db.session.add(notification)
     db.session.commit()
     assert notification in user.notifications
Esempio n. 23
0
 def test_password_setter(self):
     u = User()
     u.set_password("hello")
     assert u.password_hash is not None