import time
import yaml
import pytest
import os
import sys

from ids_list import get_ids
import path_setting
from in_common.base_request import BaseRequest
from all_backend_api.topic_reply_create_request import topic_reply_create_request

class TestTopicReplyCreate:
    data = BaseRequest().api_load(path_setting.TOPIC_REPLY_CREATE)
    topic_reply_create_case, topic_reply_create_data = get_ids(data, "reply_create")

    @pytest.mark.parametrize("param", topic_reply_create_data, ids=topic_reply_create_case)
    def test_topic_reply_create(self, param):
        r = topic_reply_create_request().topic_reply_create( param["content"], param["channel"] )
        # 一级评论三种情况校验，回复成功，回复频繁，回复重复
        if r["error"] == 0:
            assert r["message"] == param["message1"]
        elif r["error"] == 4:
            assert r["message"] == param["message"]
        elif r["error"] == 1:
            assert r["message"] == param["message2"]

        sub_r = topic_reply_create_request().topic_sub_reply_create( param["content"], param["channel"], param["replied_id"] )
        # 二级评论三种情况校验，回复成功，回复频繁，回复重复
        if sub_r["error"] == 0:
            assert sub_r["message"] == param["message1"]
        elif sub_r["error"] == 4:
            assert sub_r["message"] == param["message"]
        elif sub_r["error"] == 1:
            assert sub_r["message"] == param["message2"]


        # 运行完用例后修改topic_reply_create.yaml文件里的content内容避免下一次重复,工作路径是backend_auto，用的是相对路径
        project_path2 = os.getcwd()
        dd1 = os.path.split(project_path2)
        dd = os.path.split(project_path2)[1]
        if dd == "backend_auto":
            path_test = dd1[0] + "/backend_auto/test_backend_data/topic_data/topic_reply_create.yaml"
        elif dd == "test_backend_case":
            path_test = dd1[0] + "/test_backend_data/topic_data/topic_reply_create.yaml"
        elif dd == "topic_case":
            path_test = os.path.split(dd1[0])[0] + "/test_backend_data/topic_data/topic_reply_create.yaml"
        else:
            i = 0
            while dd != "backend_auto":
                dd1 =os.path.split(dd1[0])[0]
                dd = os.path.split(dd1)[1]
                i = i + 1
                if i > 6:
                    break
            path_test = dd1 + "/test_backend_data/topic_data/topic_reply_create.yaml"

        with open(path_test, "r", encoding="utf-8") as f:
            res = yaml.load(f, Loader=yaml.FullLoader)
            a_content = res["reply_create"][0]["content"]
            a_new_content = "ces测试+" + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
            # 更换content内容,写入yaml文件
            for k in res["reply_create"][0]:
                if k == "content":
                    res["reply_create"][0][k] = a_new_content
        with open(path_test, "w", encoding="utf-8") as f:
            yaml.dump(res, f, encoding='utf-8', allow_unicode=True)


