Esempio n. 1
0
 def test_memory_session_storage_access_token(self):
     client = WeChatClient(self.app_id, self.secret)
     with HTTMock(wechat_api_mock):
         token = client.fetch_access_token()
         self.assertEqual('1234567890', token['access_token'])
         self.assertEqual(7200, token['expires_in'])
         self.assertEqual('1234567890', client.access_token)
Esempio n. 2
0
 def test_memory_session_storage_access_token(self):
     client = WeChatClient(self.app_id, self.secret)
     with HTTMock(wechat_api_mock):
         token = client.fetch_access_token()
         self.assertEqual('1234567890', token['access_token'])
         self.assertEqual(7200, token['expires_in'])
         self.assertEqual('1234567890', client.access_token)
Esempio n. 3
0
    def get(self, request, args):
        redis_conn = get_redis_connection("default")
        access_token = redis_conn.get("access_token")
        access_token = access_token.decode("utf-8") if access_token else None
        wechat_client = WeChatClient(appid=MP_APPID,
                                     secret=MP_APPSECRET,
                                     access_token=access_token,
                                     timeout=5)
        if not access_token:
            access_token = wechat_client.fetch_access_token()
            redis_conn.setex("access_token", 3600,
                             access_token.get("access_token"))
        jsapi_ticket = redis_conn.get("jsapi_ticket")
        jsapi_ticket = jsapi_ticket.decode("utf-8") if jsapi_ticket else None
        if not jsapi_ticket:
            jsapi_ticket = wechat_client.jsapi.get_jsapi_ticket()
            redis_conn.setex("jsapi_ticket", 7100, jsapi_ticket)
        noncestr = "".join(
            random.sample(string.ascii_letters + string.digits, 10))
        timestamp = int(time.time())
        signature = wechat_client.jsapi.get_jsapi_signature(
            noncestr, jsapi_ticket, timestamp, args.get("url"))
        data = {
            "appID": MP_APPID,
            "timestamp": timestamp,
            "nonceStr": noncestr,
            "signature": signature,
        }

        return self.send_success(data=data)
Esempio n. 4
0
 def test_shove_storage_access_token(self):
     uri = "memory://"
     client = WeChatClient(self.app_id, self.secret, session=uri)
     with HTTMock(wechat_api_mock):
         token = client.fetch_access_token()
         self.assertEqual("1234567890", token["access_token"])
         self.assertEqual(7200, token["expires_in"])
         self.assertEqual("1234567890", client.access_token)
Esempio n. 5
0
    def test_shove_storage_access_token(self):
        if sys.version_info[:2] == (2, 6):
            return

        uri = 'memory://'
        client = WeChatClient(self.app_id, self.secret, session=uri)
        with HTTMock(wechat_api_mock):
            token = client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', client.access_token)
Esempio n. 6
0
    def test_shove_storage_access_token(self):
        if sys.version_info[:2] == (2, 6):
            return

        uri = 'memory://'
        client = WeChatClient(self.app_id, self.secret, session=uri)
        with HTTMock(wechat_api_mock):
            token = client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', client.access_token)
Esempio n. 7
0
    def test_redis_session_storage_access_token(self):
        from redis import Redis
        from wechatpy.session.redisstorage import RedisStorage

        redis = Redis()
        session = RedisStorage(redis)
        client = WeChatClient(self.app_id, self.secret, session=session)
        with HTTMock(wechat_api_mock):
            token = client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', client.access_token)
Esempio n. 8
0
    def test_redis_session_storage_access_token(self):
        from redis import Redis
        from wechatpy.session.redisstorage import RedisStorage

        redis = Redis()
        session = RedisStorage(redis)
        client = WeChatClient(self.app_id, self.secret, session=session)
        with HTTMock(wechat_api_mock):
            token = client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', client.access_token)
Esempio n. 9
0
    def test_client_expires_at_consistency(self):
        from redis import Redis
        from wechatpy.session.redisstorage import RedisStorage

        redis = Redis()
        session = RedisStorage(redis)
        client1 = WeChatClient(self.app_id, self.secret, session=session)
        client2 = WeChatClient(self.app_id, self.secret, session=session)
        assert client1.expires_at == client2.expires_at
        expires_at = time.time() + 7200
        client1.expires_at = expires_at
        assert client1.expires_at == client2.expires_at == expires_at
Esempio n. 10
0
def init_wechat_sdk():
    """ 初始化微信sdk
    设置保存一些参数
    """
    wechat_client = WeChatClient(current_app.config['APPID'],
                                 current_app.config['APPSECRET'])

    access_token = redis.get("wechat:access_token")
    jsapi_ticket = redis.get("wechat:jsapi_ticket")
    token_expires_at = redis.get("wechat:access_token_expires_at")
    ticket_expires_at = redis.get("wechat:jsapi_ticket_expires_at")
    if access_token and jsapi_ticket:
        wechat = {
            'client': wechat_client,
            'appid': current_app.config['APPID'],
            'appsecret': current_app.config['APPSECRET'],
            'token': current_app.config['TOKEN'],
            'access_token': access_token,
            'access_token_expires_at': int(token_expires_at),
            'jsapi_ticket': jsapi_ticket,
            'jsapi_ticket_expires_at': int(ticket_expires_at)
        }
        return wechat
    #  没有缓存
    else:
        access_token_dic = wechat_client.fetch_access_token()
        access_token = access_token_dic['access_token']
        token_expires_at = access_token_dic['expires_in']

        jsapi_ticket_dic = wechat_client.jsapi.get_ticket()
        jsapi_ticket = jsapi_ticket_dic['ticket']
        ticket_expires_at = jsapi_ticket_dic['expires_in']

        redis.set("wechat:access_token", access_token, 7000)
        redis.set("wechat:access_token_expires_at", token_expires_at, 7000)
        redis.set("wechat:jsapi_ticket", jsapi_ticket, 7000)
        redis.set("wechat:jsapi_ticket_expires_at", ticket_expires_at, 7000)

        wechat = {
            'client': wechat_client,
            'appid': current_app.config['APPID'],
            'appsecret': current_app.config['APPSECRET'],
            'token': current_app.config['TOKEN'],
            'access_token': access_token,
            'access_token_expires_at': int(token_expires_at),
            'jsapi_ticket': jsapi_ticket,
            'jsapi_ticket_expires_at': int(ticket_expires_at)
        }
        return wechat
Esempio n. 11
0
def create_menu(request):
    # 第一个参数是公众号里面的appID,第二个参数是appsecret
    client = WeChatClient("wx1c53a7cf55314e85",
                          "d28ecedbf5ff74fe268595ea035a6b6f")
    client.menu.create({
        "button": [{
            "name":
            "智能访客",
            "sub_button": [{
                "type": "view",
                "name": "访客预约",
                "url": "http://3fcba1c69bb95399.natapp.cc/wx",
                "sub_button": []
            }]
        }, {
            "name":
            "产品演示",
            "sub_button": [{
                "type": "view",
                "name": "资产管理",
                "url": "http://127.0.0.1",
                "sub_button": []
            }]
        }, {
            "type": "click",
            "name": "关于戊辰",
            "key": "V1001_GOOD"
        }]
    })
    return HttpResponse('ok')
Esempio n. 12
0
    def test_shove_storage_init(self):
        from wechatpy.session.shovestorage import ShoveStorage

        uri = 'memory://'
        client = WeChatClient(self.app_id, self.secret, session=uri)
        self.assertTrue(isinstance(client.session, ShoveStorage))
        self.assertEqual('wechatpy', client.session.prefix)
Esempio n. 13
0
def defi_menu(request):
    client = WeChatClient(APPID, APPSECRET, accessToken.send_request())
    client.menu.create({
        "button": [{
            "name":
            "公司注册",
            "sub_button": [{
                "type":
                "view",
                "name":
                "订单提交",
                "url":
                "http://whw.free.idcfengye.com/first/userInfo/"
            }, {
                "type": "view",
                "name": "进度查询",
                "url": "http://whw.free.idcfengye.com/first/check/"
            }, {
                "type": "click",
                "name": "赞一下我们",
                "key": "V1001_GOOD"
            }]
        }]
    })
    return HttpResponse('创建成功')
Esempio n. 14
0
    def test_memcached_storage_access_token(self):
        if platform.system() == 'Windows':
            return

        from pymemcache.client import Client
        from wechatpy.session.memcachedstorage import MemcachedStorage

        servers = ("127.0.0.1", 11211)
        memcached = Client(servers)
        session = MemcachedStorage(memcached)
        client = WeChatClient(self.app_id, self.secret, session=session)
        with HTTMock(wechat_api_mock):
            token = client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', client.access_token)
Esempio n. 15
0
def type_event(db: Session, message):
    if "Ticket" in message:
        client = WeChatClient(wechat.app_id, wechat.secret)
        user = crud.user.get_by_wx_openid(db, message['FromUserName'])
        # 不存在时创建用户
        if not user:
            try:
                # 获取微信
                wechat_user = client.user.get(message['FromUserName'])
            except Exception as e:
                print(e)
                nickname = "nickname" + str(random.randint(100, 999))
                headimgurl = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1517507934,1319873565&fm=26&gp=0.jpg"
                wechat_user = {
                    "openid": message['FromUserName'],
                    "nickname": nickname,
                    "headimgurl": headimgurl
                }
                # raise e
            crud.user.create_by_wechat(db=db,
                                       wx_openid=message['FromUserName'],
                                       name=wechat_user["nickname"],
                                       avatar=wechat_user["headimgurl"])
        Cache.put(message['Ticket'], message['FromUserName'], 5)
    return ''
Esempio n. 16
0
def short_urls(url):
    if not url:
        return url

    m2 = hashlib.md5()
    m2.update(url)
    fp = m2.hexdigest()
    fp = 'runtime/%s' % fp

    if os.path.exists(fp):
        with open(fp) as f:
            s = f.read()

        return s

    try:
        client = WeChatClient(settings.WECHAT_APPKEY, settings.WECHAT_SECRET)
        short_url = client.misc.short_url(long_url=url)['short_url']

        with open(fp, 'w') as f:
            f.write(short_url)
    except Exception as e:
        short_url = url

    return short_url
Esempio n. 17
0
    def wechat(cls, content):
        # pip install wechatpy
        # pip install pycrypto  cryptography  2选1

        from wechatpy import WeChatClient
        import datetime

        client = WeChatClient('oqZI700TICQqEk_LHluLxgsk2-qQ',
                              '5354b6234736845c82345e')
        template_id = 'SVxtZHeS77EvBLyzl234tifLYt-234pORiN345No'
        openid = 'oV4P22J234JcnJD3YK34567c'

        data = {
            'msg': {
                "value": content,
                "color": "#173177"
            },
            'time': {
                "value": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "color": "#173177"
            },
        }

        try:
            client.message.send_template(openid, template_id, data)
        except Exception as ex:
            print(ex)
Esempio n. 18
0
def createMenu(request):
    print("go into ajax createMenu.")
    client = WeChatClient(APPID, AppSecret)
    response = client.menu.create({
        "button": [{
            "name":
            "底价分类",
            "sub_button": [
                {
                    "type": "view",
                    "name": "团购",
                    "url": "http://39.106.98.42/djshop/wechat/groupbuyPanel"
                },
                {
                    "type": "view",
                    "name": "外卖",
                    "url": "http://39.106.98.42/djshop/wechat/takeoutPanel"
                },
                {
                    "type": "view",
                    "name": "约车",
                    "url": "http://39.106.98.42/djshop/wechat/carorderPanel"
                },
                {
                    "type": "view",
                    "name": "电影票",
                    "url": "http://39.106.98.42/djshop/wechat/moviePanel"
                },
            ]
        }, {
            "name":
            "底价消息",
            "sub_button": [
                {
                    "type": "click",
                    "name": "省钱必看",
                    "key": "piggy"
                },
                {
                    "type": "click",
                    "name": "近期优惠",
                    "key": "jasper"
                },
            ]
        }, {
            "type": "media_id",
            "name": "商务合作",
            "media_id": "Sf7M0xlLiNfkGlXla8hyVbx0TjvKPhxrs6ECOlDfmIs"
        }]
    })
    pprint.pprint(response)
    context = {
        "title": 'wechatpy.client.api.WeChatMenu.create',
        "errcode": response['errcode'],
        "errmsg": response['errmsg']
    }
    # openFile = open('/home/helen/projects/djshop/djshoproj/static/wechat/img/COACH_1.jpg', 'rb')
    # material = client.material.add('image', openFile)
    # pprint.pprint(material)
    return render(request, 'wechat/createMenu.html', context)
Esempio n. 19
0
def add_material(request):
    # 上传临时素材并且存入数据库, 注意上穿的图片名字不能是中文
    media_type = request.POST.get("media_type", "")
    # print(request.FILES.values())
    # for i in request.FILES.values():
    #     print(type(i))
    media_file = request.FILES.get("media_file")
    # print(type(media_file))
    # print(dir(media_file))
    title = request.POST.get("title", "")
    introduction = request.POST.get("introduction", "")

    # 主要是获得access_token
    client = WeChatClient('wxeac1aed88d8117f1',
                          '24397d8edd0a39d21c169a87f351c916')

    from wechatpy.client.api import WeChatMedia
    # 初始化上传临时媒体文件的类
    media = WeChatMedia(client)
    info = media.upload(media_type, media_file)
    # info = client.WeChatMedia.add(media_type, media_file.open(),title,introduction)
    print(info)
    material = MaterialModel()
    material.media_type = media_type
    material.title = title
    material.introduction = introduction
    material.media_id = info['media_id']
    material.save()
    return HttpResponse("OK")
Esempio n. 20
0
def create_menu(request):
    client = WeChatClient('wxeac1aed88d8117f1',
                          '24397d8edd0a39d21c169a87f351c916')
    client.menu.create({
        "button": [{
            "type": "click",
            "name": "今日歌曲",
            "key": "V1001_TODAY_MUSIC"
        }, {
            "type": "click",
            "name": "歌手简介",
            "key": "V1001_TODAY_SINGER"
        }, {
            "name":
            "菜单",
            "sub_button": [{
                "type": "click",
                "name": "关于我",
                'key': 'V1001_ABOUT_ME'
            }, {
                "type": "view",
                "name": "视频",
                "url": "http://v.qq.com/"
            }, {
                "type": "click",
                "name": "赞一下我们",
                "key": "V1001_GOOD"
            }]
        }]
    })
    return HttpResponse('ok')
Esempio n. 21
0
def handler(message, *args, **kwargs):
    queryset = Goods.objects.filter(title__isnull=False)
    results = queryset.all()

    if not results:
        return None

    message = '''
===================
'''
    quantity = 1

    for result in results:
        url = 'http://ws.gjingxi.com/buy/?id=%d&q=%d&uin=%s&nick=%s' % (int(
            result.id), int(quantity), uin, nick)
        client = WeChatClient(settings.WECHAT_APPKEY, settings.WECHAT_SECRET)
        short_url = client.misc.short_url(long_url=url)['short_url']

        amount = float(float(result.price) * float(quantity))
        price = result.price
        title = result.title
        units = result.units

        message += '''商品: %(title)s
价格: %(price).2f 元
%(short_url)s
-------------------
''' % locals()

    return message.strip().strip('-------------------')
Esempio n. 22
0
def wxClient():
    """
    创建微信客户端对象
    :return:
    """
    client = WeChatClient(settings.WECHAT_APPID, settings.WECHAT_SECRET, session=session_interface)
    return client
Esempio n. 23
0
def create_menu(request):
    client = WeChatClient(APPID, APPSECRET)
    client.menu.create({
        "button": [
            {
                "type": "click",
                "name": "我的博客",
                "key": "articuly_blog"
            },
            {
                "name":
                "菜单",
                "sub_button": [
                    {
                        "type": "view",
                        "name": "搜索",
                        "url": "http://www.baidu.com/"
                    },
                    {
                        "type": "click",
                        "name": "赞一下我们",
                        "key": "V1001_GOOD"
                    },
                    {
                        "name": "发送位置",
                        "type": "location_select",
                        "key": "rselfmenu_2_0"
                    },
                ]
            },
        ]
    })
    return HttpResponse('菜单已创建成功')
Esempio n. 24
0
def sendTemplate(weixin_user, message_template):
    weixin_account = WeixinAccounts.getByOriginalId(weixin_user.account_original_id)
    # account = Account.objects.get(original_id=weixin_user.account_original_id)
    client = WeChatClient(weixin_account.app_id, weixin_account.app_secret)
    client.message.send_template(weixin_user.openid, template_id=message_template.template_id,
                                 top_color=message_template.top_color, data=message_template.data,
                                 url=message_template.url)
Esempio n. 25
0
    def test_memcached_storage_access_token(self):
        if platform.system() == 'Windows':
            return

        from pymemcache.client import Client
        from wechatpy.session.memcachedstorage import MemcachedStorage

        servers = ("127.0.0.1", 11211)
        memcached = Client(servers)
        session = MemcachedStorage(memcached)
        client = WeChatClient(self.app_id, self.secret, session=session)
        with HTTMock(wechat_api_mock):
            token = client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', client.access_token)
Esempio n. 26
0
    def init_with_config(self, config):
        session_interface = self._init_session(config)

        if config['WECHAT_TYPE'] == 17:
            from wechatpy.component import WeChatComponent
            self._is_component = True
            return WeChatComponent(
                config['WECHAT_APPID'],
                config['WECHAT_SECRET'],
                config['WECHAT_TOKEN'],
                config['WECHAT_AES_KEY'],
                session=session_interface,
            )

        if config['WECHAT_TYPE'] == 0:
            from wechatpy import WeChatClient
        else:
            from wechatpy.enterprise import WeChatClient

        return WeChatClient(
            config['WECHAT_APPID'],
            config['WECHAT_SECRET'],
            session=session_interface,
            timeout=config['WECHAT_TIMEOUT'],
            auto_retry=config['WECHAT_AUTO_RETRY'],
        )
Esempio n. 27
0
    def test_shove_storage_init_with_prefix(self):
        from wechatpy.session.shovestorage import ShoveStorage

        uri = "memory://?prefix=custom_prefix"
        client = WeChatClient(self.app_id, self.secret, session=uri)
        self.assertTrue(isinstance(client.session, ShoveStorage))
        self.assertEqual("custom_prefix", client.session.prefix)
Esempio n. 28
0
def create_wechat_menu(app_name):
	print('--------------------------------------------------------')
	app_id = frappe.get_value('Wechat App', app_name, 'app_id')
	secret = frappe.get_value('Wechat App', app_name, 'secret')
	domain = "http://" + (frappe.get_value('Wechat App', app_name, 'domain') or "mm.symgrid.com")

	# Top Menu
	top_menu_list = frappe.get_all("Wechat AppMenu",
									filters={'parent': app_name, 'group_index': 0},
									fields=["menu", "alias", "`group`"],
									order_by="`group`")
	menu_buttons = []
	for menu in top_menu_list:
		doc = frappe.get_doc("Wechat Menu", menu.menu)
		menu_button = {
			"type": doc.menu_type or "view",
			"name": menu.alias or doc.menu_name
		}
		if doc.route:
			url = domain + "/wechat/" + doc.route + "/" + app_name
		else:
			url = domain + "/wechat/home/" + app_name
		menu_button["url"] = WeChatOAuth(app_id, secret, url).authorize_url

		# Sub menu
		sub_menu_list = frappe.get_all("Wechat AppMenu",
										filters={'parent': app_name, '`group`': menu.group},
										fields=["menu", "alias", "group_index"],
										order_by="group_index")

		for sub_menu in sub_menu_list:
			if sub_menu.group_index == 0:
				continue
			if "sub_button" not in menu_button:
				menu_button = {
					"name": menu_button['name'],
					"sub_button": []
				}
			doc = frappe.get_doc("Wechat Menu", sub_menu.menu)
			m = {
				"type": doc.menu_type or "view",
				"name": sub_menu.alias or doc.menu_name
			}
			if doc.route:
				url = domain + "/wechat/" + doc.route + "/" + app_name
			else:
				url = domain + "/wechat/home/" + app_name
			m["url"] = WeChatOAuth(app_id, secret, url).authorize_url
			menu_button["sub_button"].append(m)

		menu_buttons.append(menu_button)

	menu = {
		"button": menu_buttons
	}
	print(json.dumps(menu))
	client = WeChatClient(app_id, secret)
	client.menu.create(menu)
	print('--------------------------------------------------------')
Esempio n. 29
0
 def init_app(self, app):
     """从 flask app 中初始化
     """
     self.wx_client = WeChatClient(app.config.get('WX_APP_ID'),
                                   app.config.get('WX_SECRET'))
     self.handlers = []
     for handler_class in default_handlers:
         self.register_handler(handler_class(wx_client=self.wx_client))
Esempio n. 30
0
 def test_two_client_not_equal(self):
     client2 = WeChatClient('654321', '654321', '987654321')
     assert self.client != client2
     assert self.client.user != client2.user
     assert id(self.client.menu) != id(client2.menu)
     with HTTMock(wechat_api_mock):
         self.client.fetch_access_token()
         assert self.client.access_token != client2.access_token
Esempio n. 31
0
    def test_redis_session_storage_init(self):
        from redis import Redis
        from wechatpy.session.redisstorage import RedisStorage

        redis = Redis()
        session = RedisStorage(redis)
        client = WeChatClient(self.app_id, self.secret, session=session)
        self.assertTrue(isinstance(client.session, RedisStorage))
Esempio n. 32
0
def init_template_message():
    """发送模板文本消息"""

    client = WeChatClient(WECHAT_APPID, WECHAT_SECRET)
    # res = client.template.set_industry(1, 4)
    # print('>>>', res)
    res = client.template.get_industry()
    print('>>>', res)
Esempio n. 33
0
def create_wechat_menu():
    """create wechat menu"""

    print('>>>>', WECHAT_APPID, WECHAT_SECRET)
    client = WeChatClient(WECHAT_APPID, WECHAT_SECRET)

    with open(WECHAT_MENU_FILE) as f:
        client.menu.create(json.load(f))
Esempio n. 34
0
 def test_two_client_not_equal(self):
     client2 = WeChatClient("654321", "654321", "987654321")
     self.assertNotEqual(self.client, client2)
     self.assertNotEqual(self.client.user, client2.user)
     self.assertNotEqual(id(self.client.menu), id(client2.menu))
     with HTTMock(wechat_api_mock):
         self.client.fetch_access_token()
         self.assertNotEqual(self.client.access_token, client2.access_token)
Esempio n. 35
0
class WeChatClientTestCase(unittest.TestCase):

    app_id = '123456'
    secret = '123456'

    def setUp(self):
        self.client = WeChatClient(self.app_id, self.secret)

    def test_two_client_not_equal(self):
        client2 = WeChatClient('654321', '654321', '987654321')
        assert self.client != client2
        assert self.client.user != client2.user
        assert id(self.client.menu) != id(client2.menu)
        with HTTMock(wechat_api_mock):
            self.client.fetch_access_token()
            assert self.client.access_token != client2.access_token

    def test_fetch_access_token(self):
        with HTTMock(wechat_api_mock):
            token = self.client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', self.client.access_token)

    def test_upload_media(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            media = self.client.media.upload('image', media_file)
            self.assertEqual('image', media['type'])
            self.assertEqual('12345678', media['media_id'])

    def test_user_get_group_id(self):
        with HTTMock(wechat_api_mock):
            group_id = self.client.user.get_group_id('123456')
            self.assertEqual(102, group_id)

    def test_create_group(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.create('test')
            self.assertEqual(1, group['group']['id'])
            self.assertEqual('test', group['group']['name'])

    def test_group_get(self):
        with HTTMock(wechat_api_mock):
            groups = self.client.group.get()
            self.assertEqual(5, len(groups))

    def test_group_getid(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.get('123456')
            self.assertEqual(102, group)

    def test_group_update(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.update(102, 'test')
            self.assertEqual(0, result['errcode'])

    def test_group_move_user(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.move_user('test', 102)
            self.assertEqual(0, result['errcode'])

    def test_group_delete(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.delete(123456)
            self.assertEqual(0, result['errcode'])

    def test_send_text_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_text(1, 'test', account='test')
            self.assertEqual(0, result['errcode'])

    def test_send_image_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_image(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_voice_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_voice(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_video_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_video(
                1, '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_music_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_music(
                1, 'http://www.qq.com', 'http://www.qq.com',
                '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_articles_message(self):
        with HTTMock(wechat_api_mock):
            articles = [{
                'title': 'test',
                'description': 'test',
                'url': 'http://www.qq.com',
                'image': 'http://www.qq.com'
            }]
            result = self.client.message.send_articles(1, articles)
            self.assertEqual(0, result['errcode'])

    def test_get_mass_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.get_mass(201053012)
            self.assertEqual('SEND_SUCCESS', result['msg_status'])

    def test_create_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.create({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])

    def test_get_menu(self):
        with HTTMock(wechat_api_mock):
            menu = self.client.menu.get()
            self.assertTrue('menu' in menu)

    def test_delete_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.delete()
            self.assertEqual(0, result['errcode'])

    def test_update_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.update({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])

    def test_short_url(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.short_url('http://www.qq.com')
            self.assertEqual('http://qq.com', result['short_url'])

    def test_get_wechat_ips(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.get_wechat_ips()
            self.assertEqual(['127.0.0.1'], result)

    def test_get_user_info(self):
        with HTTMock(wechat_api_mock):
            openid = 'o6_bmjrPTlm6_2sgVt7hMZOPfL2M'
            user = self.client.user.get(openid)
            self.assertEqual('Band', user['nickname'])

    def test_get_followers(self):
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_followers()
            self.assertEqual(2, result['total'])
            self.assertEqual(2, result['count'])

    def test_update_user_remark(self):
        with HTTMock(wechat_api_mock):
            openid = 'openid'
            remark = 'test'
            result = self.client.user.update_remark(openid, remark)
            self.assertEqual(0, result['errcode'])

    def test_get_user_info_batch(self):
        user_list = [
            {
                "openid": "otvxTs4dckWG7imySrJd6jSi0CWE",
                "lang": "zh-CN"
            },
            {
                "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg",
                "lang": "zh-CN"
            }
        ]
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_batch(user_list)
            self.assertEqual(user_list[0]['openid'], result[0]['openid'])
            self.assertEqual('iWithery', result[0]['nickname'])
            self.assertEqual(user_list[1]['openid'], result[1]['openid'])

    def test_create_qrcode(self):
        data = {
            'expire_seconds': 1800,
            'action_name': 'QR_SCENE',
            'action_info': {
                'scene': {'scene_id': 123}
            }
        }
        with HTTMock(wechat_api_mock):
            result = self.client.qrcode.create(data)
            self.assertEqual(1800, result['expire_seconds'])

    def test_get_qrcode_url_with_str_ticket(self):
        ticket = '123'
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual(
            'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123',
            url
        )

    def test_get_qrcode_url_with_dict_ticket(self):
        ticket = {
            'ticket': '123',
        }
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual(
            'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123',
            url
        )

    def test_customservice_add_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.add_account(
                'test1@test',
                'test1',
                'test1'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_update_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.update_account(
                'test1@test',
                'test1',
                'test1'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_delete_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.delete_account(
                'test1@test',
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_upload_headimg(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.upload_headimg(
                'test1@test',
                media_file
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_get_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_get_online_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_online_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_create_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.create_session(
                'openid',
                'test1@test'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_close_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.close_session(
                'openid',
                'test1@test'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_get_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session('openid')
            self.assertEqual('test1@test', result['kf_account'])

    def test_customservice_get_session_list(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session_list('test1@test')
            self.assertEqual(2, len(result))

    def test_customservice_get_wait_case(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_wait_case()
            self.assertEqual(150, result['count'])

    def test_customservice_get_records(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_records(
                123456789,
                987654321,
                1
            )
            self.assertEqual(2, len(result))

    def test_datacube_get_user_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_cumulate(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_cumulate(
                datetime(2014, 12, 6),
                datetime(2014, 12, 7)
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_article_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_article_total(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_total(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_share(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(2, len(result))

    def test_datacube_get_user_share_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_week(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_month(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_week(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_month(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_jsapi_get_ticket(self):
        with HTTMock(wechat_api_mock):
            result = self.client.jsapi.get_ticket()
            self.assertEqual(
                'bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA',  # NOQA
                result['ticket']
            )
            self.assertEqual(7200, result['expires_in'])

    def test_jsapi_get_jsapi_signature(self):
        noncestr = 'Wm3WZYTPz0wzccnW'
        ticket = 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg'  # NOQA
        timestamp = 1414587457
        url = 'http://mp.weixin.qq.com?params=value'
        signature = self.client.jsapi.get_jsapi_signature(
            noncestr,
            ticket,
            timestamp,
            url
        )
        self.assertEqual(
            '0f9de62fce790f9a083d5c99e95740ceb90c27ed',
            signature
        )

    def test_menu_get_menu_info(self):
        with HTTMock(wechat_api_mock):
            menu_info = self.client.menu.get_menu_info()
            self.assertEqual(1, menu_info['is_menu_open'])

    def test_message_get_autoreply_info(self):
        with HTTMock(wechat_api_mock):
            autoreply = self.client.message.get_autoreply_info()
            self.assertEqual(1, autoreply['is_autoreply_open'])

    def test_shakearound_apply_device_id(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.apply_device_id(1, 'test')
            self.assertEqual(123, res['apply_id'])

    def test_shakearound_update_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.update_device('1234', comment='test')
            self.assertEqual(0, res['errcode'])

    def test_shakearound_bind_device_location(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.bind_device_location(123, 1234)
            self.assertEqual(0, res['errcode'])

    def test_shakearound_search_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.search_device(apply_id=123)
            self.assertEqual(151, res['total_count'])
            self.assertEqual(2, len(res['devices']))

    def test_shakearound_add_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.add_page(
                'test',
                'test',
                'http://www.qq.com',
                'http://www.qq.com'
            )
            self.assertEqual(28840, res['page_id'])

    def test_shakearound_update_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.update_page(
                123,
                'test',
                'test',
                'http://www.qq.com',
                'http://www.qq.com'
            )
            self.assertEqual(28840, res['page_id'])

    def test_shakearound_delete_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.delete_pages(123)
            self.assertEqual(0, res['errcode'])

    def test_shakearound_search_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.search_pages(123)
            self.assertEqual(2, res['total_count'])
            self.assertEqual(2, len(res['pages']))

    def test_shakearound_add_material(self):
        with HTTMock(wechat_api_mock):
            media_file = six.StringIO('nothing')
            res = self.client.shakearound.add_material(media_file)
            self.assertEqual(
                'http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120',  # NOQA
                res['pic_url']
            )

    def test_shakearound_bind_device_pages(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.bind_device_pages(
                123,
                1,
                1,
                1234
            )
            self.assertEqual(0, res['errcode'])

    def test_shakearound_get_shake_info(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_shake_info('123456')
            self.assertEqual(14211, res['page_id'])
            self.assertEqual('oVDmXjp7y8aG2AlBuRpMZTb1-cmA', res['openid'])

    def test_shakearound_get_device_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_device_statistics(
                '2015-04-01 00:00:00',
                '2015-04-17 00:00:00',
                1234
            )
            self.assertEqual(2, len(res))

    def test_shakearound_get_page_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_page_statistics(
                '2015-04-01 00:00:00',
                '2015-04-17 00:00:00',
                1234
            )
            self.assertEqual(2, len(res))

    def test_material_get_count(self):
        with HTTMock(wechat_api_mock):
            res = self.client.material.get_count()
            self.assertEqual(1, res['voice_count'])
            self.assertEqual(2, res['video_count'])
            self.assertEqual(3, res['image_count'])
            self.assertEqual(4, res['news_count'])

    def test_reraise_requests_exception(self):
        @urlmatch(netloc=r'(.*\.)?api\.weixin\.qq\.com$')
        def _wechat_api_mock(url, request):
            return {'status_code': 404, 'content': '404 not found'}

        try:
            with HTTMock(_wechat_api_mock):
                self.client.material.get_count()
        except WeChatClientException as e:
            self.assertEqual(404, e.response.status_code)
Esempio n. 36
0
class WeChatClientTestCase(unittest.TestCase):

    app_id = '123456'
    secret = '123456'

    def setUp(self):
        self.client = WeChatClient(self.app_id, self.secret)

    def test_fetch_access_token(self):
        with HTTMock(wechat_api_mock):
            token = self.client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', self.client.access_token)

    def test_upload_media(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            media = self.client.media.upload('image', media_file)
            self.assertEqual('image', media['type'])
            self.assertEqual('12345678', media['media_id'])

    def test_create_group(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.create('test')
            self.assertEqual(1, group['group']['id'])
            self.assertEqual('test', group['group']['name'])

    def test_group_get(self):
        with HTTMock(wechat_api_mock):
            groups = self.client.group.get()
            self.assertEqual(5, len(groups))

    def test_group_getid(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.get('123456')
            self.assertEqual(102, group)

    def test_group_update(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.update(102, 'test')
            self.assertEqual(0, result['errcode'])

    def test_group_move_user(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.move_user('test', 102)
            self.assertEqual(0, result['errcode'])

    def test_send_text_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_text(1, 'test')
            self.assertEqual(0, result['errcode'])

    def test_send_image_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_image(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_voice_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_voice(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_video_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_video(
                1, '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_music_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_music(
                1, 'http://www.qq.com', 'http://www.qq.com',
                '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_articles_message(self):
        with HTTMock(wechat_api_mock):
            articles = [{
                'title': 'test',
                'description': 'test',
                'url': 'http://www.qq.com',
                'image': 'http://www.qq.com'
            }]
            result = self.client.message.send_articles(1, articles)
            self.assertEqual(0, result['errcode'])

    def test_create_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.create({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])

    def test_get_menu(self):
        with HTTMock(wechat_api_mock):
            menu = self.client.menu.get()
            self.assertTrue('menu' in menu)

    def test_delete_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.delete()
            self.assertEqual(0, result['errcode'])

    def test_update_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.update({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])

    def test_short_url(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.short_url('http://www.qq.com')
            self.assertEqual('http://qq.com', result['short_url'])

    def test_get_wechat_ips(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.get_wechat_ips()
            self.assertEqual(['127.0.0.1'], result)

    def test_get_user_info(self):
        with HTTMock(wechat_api_mock):
            openid = 'o6_bmjrPTlm6_2sgVt7hMZOPfL2M'
            user = self.client.user.get(openid)
            self.assertEqual('Band', user['nickname'])

    def test_get_followers(self):
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_followers()
            self.assertEqual(2, result['total'])
            self.assertEqual(2, result['count'])

    def test_update_user_remark(self):
        with HTTMock(wechat_api_mock):
            openid = 'openid'
            remark = 'test'
            result = self.client.user.update_remark(openid, remark)
            self.assertEqual(0, result['errcode'])

    def test_create_qrcode(self):
        data = {
            'expire_seconds': 1800,
            'action_name': 'QR_SCENE',
            'action_info': {
                'scene': {'scene_id': 123}
            }
        }
        with HTTMock(wechat_api_mock):
            result = self.client.qrcode.create(data)
            self.assertEqual(1800, result['expire_seconds'])

    def test_get_qrcode_url_with_str_ticket(self):
        ticket = '123'
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual(
            'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123',
            url
        )

    def test_get_qrcode_url_with_dict_ticket(self):
        ticket = {
            'ticket': '123',
        }
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual(
            'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123',
            url
        )

    def test_customservice_add_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.add_account(
                'test1@test',
                'test1',
                'test1'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_update_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.update_account(
                'test1@test',
                'test1',
                'test1'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_delete_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.delete_account(
                'test1@test',
                'test1',
                'test1'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_upload_headimg(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.upload_headimg(
                'test1@test',
                media_file
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_get_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_get_online_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_online_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_create_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.create_session(
                'openid',
                'test1@test'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_close_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.close_session(
                'openid',
                'test1@test'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_get_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session('openid')
            self.assertEqual('test1@test', result['kf_account'])

    def test_customservice_get_session_list(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session_list('test1@test')
            self.assertEqual(2, len(result))

    def test_customservice_get_wait_case(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_wait_case()
            self.assertEqual(150, result['count'])

    def test_datacube_get_user_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_cumulate(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_cumulate(
                datetime(2014, 12, 6),
                datetime(2014, 12, 7)
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_article_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_article_total(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_total(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_share(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(2, len(result))

    def test_datacube_get_user_share_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_week(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_month(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_week(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_month(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_jsapi_get_ticket(self):
        with HTTMock(wechat_api_mock):
            result = self.client.jsapi.get_ticket()
            self.assertEqual(
                'bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA',  # NOQA
                result['ticket']
            )
            self.assertEqual(7200, result['expires_in'])

    def test_jsapi_get_jsapi_signature(self):
        noncestr = 'Wm3WZYTPz0wzccnW'
        ticket = 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg'  # NOQA
        timestamp = 1414587457
        url = 'http://mp.weixin.qq.com?params=value'
        signature = self.client.jsapi.get_jsapi_signature(
            noncestr,
            ticket,
            timestamp,
            url
        )
        self.assertEqual(
            '0f9de62fce790f9a083d5c99e95740ceb90c27ed',
            signature
        )
Esempio n. 37
0
def getWeChatToken():
    client = WeChatClient(WECHAT_OFICAL_APPID, WECHAT_OFICAL_SCERCT)
    info = client.fetch_access_token()
    print(info)
Esempio n. 38
0
class WeChatClientTestCase(unittest.TestCase):
    app_id = '123456'
    secret = '123456'

    def setUp(self):
        self.client = WeChatClient(self.app_id, self.secret)

    def test_two_client_not_equal(self):
        client2 = WeChatClient('654321', '654321', '987654321')
        assert self.client != client2
        assert self.client.user != client2.user
        assert id(self.client.menu) != id(client2.menu)
        with HTTMock(wechat_api_mock):
            self.client.fetch_access_token()
            assert self.client.access_token != client2.access_token

    def test_subclass_client_ok(self):
        class TestClient(WeChatClient):
            pass

        client = TestClient('12345', '123456', '123456789')
        self.assertEqual(client, client.user._client)

    def test_fetch_access_token(self):
        with HTTMock(wechat_api_mock):
            token = self.client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', self.client.access_token)

    def test_upload_media(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            media = self.client.media.upload('image', media_file)
            self.assertEqual('image', media['type'])
            self.assertEqual('12345678', media['media_id'])

    def test_user_get_group_id(self):
        with HTTMock(wechat_api_mock):
            group_id = self.client.user.get_group_id('123456')
            self.assertEqual(102, group_id)

    def test_create_group(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.create('test')
            self.assertEqual(1, group['group']['id'])
            self.assertEqual('test', group['group']['name'])

    def test_group_get(self):
        with HTTMock(wechat_api_mock):
            groups = self.client.group.get()
            self.assertEqual(5, len(groups))

    def test_group_getid(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.get('123456')
            self.assertEqual(102, group)

    def test_group_update(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.update(102, 'test')
            self.assertEqual(0, result['errcode'])

    def test_group_move_user(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.move_user('test', 102)
            self.assertEqual(0, result['errcode'])

    def test_group_delete(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.delete(123456)
            self.assertEqual(0, result['errcode'])

    def test_send_text_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_text(1, 'test', account='test')
            self.assertEqual(0, result['errcode'])

    def test_send_image_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_image(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_voice_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_voice(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_video_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_video(
                1, '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_music_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_music(
                1, 'http://www.qq.com', 'http://www.qq.com',
                '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_articles_message(self):
        with HTTMock(wechat_api_mock):
            articles = [{
                'title': 'test',
                'description': 'test',
                'url': 'http://www.qq.com',
                'image': 'http://www.qq.com'
            }]
            result = self.client.message.send_articles(1, articles)
            self.assertEqual(0, result['errcode'])

    def test_send_card_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_card(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_mini_program_page(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_mini_program_page(1, {})
            self.assertEqual(0, result['errcode'])

    def test_send_mass_text_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_mass_text([1], 'test', is_to_all=True)
            self.assertEqual(0, result['errcode'])

    def test_send_mass_image_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_mass_image([1], '123456', is_to_all=True)
            self.assertEqual(0, result['errcode'])

    def test_send_mass_voice_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_mass_voice([1], 'test', is_to_all=True)
            self.assertEqual(0, result['errcode'])

    def test_send_mass_video_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_mass_video([1], 'test', title='title', description='desc', is_to_all=True)
            self.assertEqual(0, result['errcode'])

    def test_send_mass_article_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_mass_article([1], 'test', is_to_all=True)
            self.assertEqual(0, result['errcode'])

    def test_send_mass_card_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_mass_card([1], 'test', is_to_all=True)
            self.assertEqual(0, result['errcode'])

    def test_get_mass_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.get_mass(201053012)
            self.assertEqual('SEND_SUCCESS', result['msg_status'])

    def test_create_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.create({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])

    def test_get_menu(self):
        with HTTMock(wechat_api_mock):
            menu = self.client.menu.get()
            self.assertTrue('menu' in menu)

    def test_delete_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.delete()
            self.assertEqual(0, result['errcode'])

    def test_update_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.update({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])

    def test_short_url(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.short_url('http://www.qq.com')
            self.assertEqual('http://qq.com', result['short_url'])

    def test_get_wechat_ips(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.get_wechat_ips()
            self.assertEqual(['127.0.0.1'], result)

    def test_get_user_info(self):
        with HTTMock(wechat_api_mock):
            openid = 'o6_bmjrPTlm6_2sgVt7hMZOPfL2M'
            user = self.client.user.get(openid)
            self.assertEqual('Band', user['nickname'])

    def test_get_followers(self):
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_followers()
            self.assertEqual(2, result['total'])
            self.assertEqual(2, result['count'])

    def test_update_user_remark(self):
        with HTTMock(wechat_api_mock):
            openid = 'openid'
            remark = 'test'
            result = self.client.user.update_remark(openid, remark)
            self.assertEqual(0, result['errcode'])

    def test_get_user_info_batch(self):
        user_list = [
            {
                "openid": "otvxTs4dckWG7imySrJd6jSi0CWE",
                "lang": "zh-CN"
            },
            {
                "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg",
                "lang": "zh-CN"
            }
        ]
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_batch(user_list)
            self.assertEqual(user_list[0]['openid'], result[0]['openid'])
            self.assertEqual('iWithery', result[0]['nickname'])
            self.assertEqual(user_list[1]['openid'], result[1]['openid'])

    def test_get_user_info_batch_openid_list(self):
        user_list = [
            'otvxTs4dckWG7imySrJd6jSi0CWE',
            'otvxTs_JZ6SEiP0imdhpi50fuSZg'
        ]
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_batch(user_list)
            self.assertEqual(user_list[0], result[0]['openid'])
            self.assertEqual('iWithery', result[0]['nickname'])
            self.assertEqual(user_list[1], result[1]['openid'])

    def test_create_qrcode(self):
        data = {
            'expire_seconds': 1800,
            'action_name': 'QR_SCENE',
            'action_info': {
                'scene': {'scene_id': 123}
            }
        }
        with HTTMock(wechat_api_mock):
            result = self.client.qrcode.create(data)
            self.assertEqual(1800, result['expire_seconds'])

    def test_get_qrcode_url_with_str_ticket(self):
        ticket = '123'
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual(
            'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123',
            url
        )

    def test_get_qrcode_url_with_dict_ticket(self):
        ticket = {
            'ticket': '123',
        }
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual(
            'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123',
            url
        )

    def test_customservice_add_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.add_account(
                'test1@test',
                'test1',
                'test1'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_update_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.update_account(
                'test1@test',
                'test1',
                'test1'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_delete_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.delete_account(
                'test1@test',
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_upload_headimg(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.upload_headimg(
                'test1@test',
                media_file
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_get_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_get_online_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_online_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_create_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.create_session(
                'openid',
                'test1@test'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_close_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.close_session(
                'openid',
                'test1@test'
            )
            self.assertEqual(0, result['errcode'])

    def test_customservice_get_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session('openid')
            self.assertEqual('test1@test', result['kf_account'])

    def test_customservice_get_session_list(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session_list('test1@test')
            self.assertEqual(2, len(result))

    def test_customservice_get_wait_case(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_wait_case()
            self.assertEqual(150, result['count'])

    def test_customservice_get_records(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_records(
                123456789,
                987654321,
                1
            )
            self.assertEqual(2, len(result['recordlist']))

    def test_datacube_get_user_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_cumulate(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_cumulate(
                datetime(2014, 12, 6),
                datetime(2014, 12, 7)
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_article_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_summary(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_article_total(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_total(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_user_share(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(2, len(result))

    def test_datacube_get_user_share_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_hour(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_week(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_month(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_week(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_month(
                '2014-12-06',
                '2014-12-07'
            )
            self.assertEqual(1, len(result))

    def test_jsapi_get_ticket_response(self):
        with HTTMock(wechat_api_mock):
            result = self.client.jsapi.get_ticket()
            self.assertEqual(
                'bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA',  # NOQA
                result['ticket']
            )
            self.assertEqual(7200, result['expires_in'])

    def test_jsapi_get_jsapi_signature(self):
        noncestr = 'Wm3WZYTPz0wzccnW'
        ticket = 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg'  # NOQA
        timestamp = 1414587457
        url = 'http://mp.weixin.qq.com?params=value'
        signature = self.client.jsapi.get_jsapi_signature(
            noncestr,
            ticket,
            timestamp,
            url
        )
        self.assertEqual(
            '0f9de62fce790f9a083d5c99e95740ceb90c27ed',
            signature
        )

    def test_jsapi_get_jsapi_card_ticket(self):
        """card_ticket 与 jsapi_ticket 的 api 都相同,除了请求参数 type 为 wx_card
        所以这里使用与 `test_jsapi_get_ticket` 相同的测试文件"""
        with HTTMock(wechat_api_mock):
            ticket = self.client.jsapi.get_jsapi_card_ticket()
            self.assertEqual(
                'bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA',  # NOQA
                ticket
            )
            self.assertTrue(7200 < self.client.session.get('{0}_jsapi_card_ticket_expires_at'.format(self.client.appid)))
            self.assertEqual(
                self.client.session.get('{0}_jsapi_card_ticket'.format(self.client.appid)),
                'bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA',
            )

    def test_jsapi_get_jsapi_card_params(self):
        """微信签名测试工具:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=cardsign"""
        noncestr = 'Wm3WZYTPz0wzccnW'
        card_ticket = 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg'
        timestamp = 1414587457
        signature_dict = self.client.jsapi.get_jsapi_card_params(
            noncestr=noncestr,
            card_ticket=card_ticket,
            timestamp=timestamp,
            card_type='GROUPON',
        )
        self.assertEqual(
            {'card_type': 'GROUPON', 'noncestr': 'Wm3WZYTPz0wzccnW',
             'api_ticket': 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg',
             'appid': '123456', 'timestamp': 1414587457, 'sign': 'c47b1fb500eb35d8f2f9b9375b4491089df953e2'},
            signature_dict
        )

    def test_menu_get_menu_info(self):
        with HTTMock(wechat_api_mock):
            menu_info = self.client.menu.get_menu_info()
            self.assertEqual(1, menu_info['is_menu_open'])

    def test_message_get_autoreply_info(self):
        with HTTMock(wechat_api_mock):
            autoreply = self.client.message.get_autoreply_info()
            self.assertEqual(1, autoreply['is_autoreply_open'])

    def test_shakearound_apply_device_id(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.apply_device_id(1, 'test')
            self.assertEqual(123, res['apply_id'])

    def test_shakearound_update_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.update_device('1234', comment='test')
            self.assertEqual(0, res['errcode'])

    def test_shakearound_bind_device_location(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.bind_device_location(123, 1234)
            self.assertEqual(0, res['errcode'])

    def test_shakearound_search_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.search_device(apply_id=123)
            self.assertEqual(151, res['total_count'])
            self.assertEqual(2, len(res['devices']))

    def test_shakearound_add_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.add_page(
                'test',
                'test',
                'http://www.qq.com',
                'http://www.qq.com'
            )
            self.assertEqual(28840, res['page_id'])

    def test_shakearound_update_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.update_page(
                123,
                'test',
                'test',
                'http://www.qq.com',
                'http://www.qq.com'
            )
            self.assertEqual(28840, res['page_id'])

    def test_shakearound_delete_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.delete_page(123)
            self.assertEqual(0, res['errcode'])

    def test_shakearound_search_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.search_pages(123)
            self.assertEqual(2, res['total_count'])
            self.assertEqual(2, len(res['pages']))

    def test_shakearound_add_material(self):
        with HTTMock(wechat_api_mock):
            media_file = six.StringIO('nothing')
            res = self.client.shakearound.add_material(media_file, 'icon')
            self.assertEqual(
                'http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120',  # NOQA
                res['pic_url']
            )

    def test_shakearound_bind_device_pages(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.bind_device_pages(
                123,
                1,
                1,
                1234
            )
            self.assertEqual(0, res['errcode'])

    def test_shakearound_get_shake_info(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_shake_info('123456')
            self.assertEqual(14211, res['page_id'])
            self.assertEqual('oVDmXjp7y8aG2AlBuRpMZTb1-cmA', res['openid'])

    def test_shakearound_get_device_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_device_statistics(
                '2015-04-01 00:00:00',
                '2015-04-17 00:00:00',
                1234
            )
            self.assertEqual(2, len(res))

    def test_shakearound_get_page_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_page_statistics(
                '2015-04-01 00:00:00',
                '2015-04-17 00:00:00',
                1234
            )
            self.assertEqual(2, len(res))

    def test_material_get_count(self):
        with HTTMock(wechat_api_mock):
            res = self.client.material.get_count()
            self.assertEqual(1, res['voice_count'])
            self.assertEqual(2, res['video_count'])
            self.assertEqual(3, res['image_count'])
            self.assertEqual(4, res['news_count'])

    def test_shakearound_get_apply_status(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_apply_status(
                1234
            )
            self.assertEqual(4, len(res))

    def test_reraise_requests_exception(self):
        @urlmatch(netloc=r'(.*\.)?api\.weixin\.qq\.com$')
        def _wechat_api_mock(url, request):
            return {'status_code': 404, 'content': '404 not found'}

        try:
            with HTTMock(_wechat_api_mock):
                self.client.material.get_count()
        except WeChatClientException as e:
            self.assertEqual(404, e.response.status_code)

    def test_wifi_list_shops(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.list_shops()
            self.assertEqual(16, res['totalcount'])
            self.assertEqual(1, res['pageindex'])

    def test_wifi_get_shop(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.get_shop(1)
            self.assertEqual(1, res['bar_type'])
            self.assertEqual(2, res['ap_count'])

    def test_wifi_add_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.add_device(
                123, 'WX-test', '12345678', '00:1f:7a:ad:5c:a8'
            )
            self.assertEqual(0, res['errcode'])

    def test_wifi_list_devices(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.list_devices()
            self.assertEqual(2, res['totalcount'])
            self.assertEqual(1, res['pageindex'])

    def test_wifi_delete_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.delete_device('00:1f:7a:ad:5c:a8')
            self.assertEqual(0, res['errcode'])

    def test_wifi_get_qrcode_url(self):
        with HTTMock(wechat_api_mock):
            qrcode_url = self.client.wifi.get_qrcode_url(123, 0)
            self.assertEqual('http://www.qq.com', qrcode_url)

    def test_wifi_set_homepage(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.set_homepage(123, 0)
            self.assertEqual(0, res['errcode'])

    def test_wifi_get_homepage(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.get_homepage(429620)
            self.assertEqual(1, res['template_id'])
            self.assertEqual('http://wifi.weixin.qq.com/', res['url'])

    def test_wifi_list_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.list_statistics('2015-05-01', '2015-05-02')
            self.assertEqual(2, len(res))

    def test_upload_mass_image(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            res = self.client.media.upload_mass_image(media_file)
        self.assertEqual(
            'http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYs CNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0',  # NOQA
            res
        )

    def test_scan_get_merchant_info(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.get_merchant_info()
        self.assertEqual(8888, res['verified_firm_code_list'][0])

    def test_scan_create_product(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.create_product({
                "keystandard": "ean13",
                "keystr": "6900000000000",
            })
        self.assertEqual('5g0B4A90aqc', res['pid'])

    def test_scan_publish_product(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.publish_product('ean13', '6900873042720')
        self.assertEqual(0, res['errcode'])

    def test_scan_unpublish_product(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.unpublish_product('ean13', '6900873042720')
        self.assertEqual(0, res['errcode'])

    def test_scan_set_test_whitelist(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.set_test_whitelist(['openid1'], ['messense'])
        self.assertEqual(0, res['errcode'])

    def test_scan_get_product(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.get_product('ean13', '6900873042720')
        assert 'brand_info' in res

    def test_scan_list_product(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.list_product()
        self.assertEqual(2, res['total'])

    def test_scan_update_product(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.update_product({
                "keystandard": "ean13",
                "keystr": "6900000000000",
            })
        self.assertEqual('5g0B4A90aqc', res['pid'])

    def test_scan_clear_product(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.clear_product('ean13', '6900873042720')
        self.assertEqual(0, res['errcode'])

    def test_scan_check_ticket(self):
        with HTTMock(wechat_api_mock):
            res = self.client.scan.check_ticket('Ym1haDlvNXJqY3Ru1')
        self.assertEqual('otAzGjrS4AYCmeJM1GhEOcHXXTAo', res['openid'])
Esempio n. 39
0
class WeChatClientTestCase(unittest.TestCase):

    app_id = "123456"
    secret = "123456"

    def setUp(self):
        self.client = WeChatClient(self.app_id, self.secret)

    def test_two_client_not_equal(self):
        client2 = WeChatClient("654321", "654321", "987654321")
        assert self.client != client2
        assert self.client.user != client2.user
        assert id(self.client.menu) != id(client2.menu)
        with HTTMock(wechat_api_mock):
            self.client.fetch_access_token()
            assert self.client.access_token != client2.access_token

    def test_subclass_client_ok(self):
        class TestClient(WeChatClient):
            pass

        client = TestClient("12345", "123456", "123456789")
        self.assertEqual(client, client.user._client)

    def test_fetch_access_token(self):
        with HTTMock(wechat_api_mock):
            token = self.client.fetch_access_token()
            self.assertEqual("1234567890", token["access_token"])
            self.assertEqual(7200, token["expires_in"])
            self.assertEqual("1234567890", self.client.access_token)

    def test_upload_media(self):
        media_file = six.StringIO("nothing")
        with HTTMock(wechat_api_mock):
            media = self.client.media.upload("image", media_file)
            self.assertEqual("image", media["type"])
            self.assertEqual("12345678", media["media_id"])

    def test_user_get_group_id(self):
        with HTTMock(wechat_api_mock):
            group_id = self.client.user.get_group_id("123456")
            self.assertEqual(102, group_id)

    def test_create_group(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.create("test")
            self.assertEqual(1, group["group"]["id"])
            self.assertEqual("test", group["group"]["name"])

    def test_group_get(self):
        with HTTMock(wechat_api_mock):
            groups = self.client.group.get()
            self.assertEqual(5, len(groups))

    def test_group_getid(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.get("123456")
            self.assertEqual(102, group)

    def test_group_update(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.update(102, "test")
            self.assertEqual(0, result["errcode"])

    def test_group_move_user(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.move_user("test", 102)
            self.assertEqual(0, result["errcode"])

    def test_group_delete(self):
        with HTTMock(wechat_api_mock):
            result = self.client.group.delete(123456)
            self.assertEqual(0, result["errcode"])

    def test_send_text_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_text(1, "test", account="test")
            self.assertEqual(0, result["errcode"])

    def test_send_image_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_image(1, "123456")
            self.assertEqual(0, result["errcode"])

    def test_send_voice_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_voice(1, "123456")
            self.assertEqual(0, result["errcode"])

    def test_send_video_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_video(1, "123456", "test", "test")
            self.assertEqual(0, result["errcode"])

    def test_send_music_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_music(
                1, "http://www.qq.com", "http://www.qq.com", "123456", "test", "test"
            )
            self.assertEqual(0, result["errcode"])

    def test_send_articles_message(self):
        with HTTMock(wechat_api_mock):
            articles = [
                {"title": "test", "description": "test", "url": "http://www.qq.com", "image": "http://www.qq.com"}
            ]
            result = self.client.message.send_articles(1, articles)
            self.assertEqual(0, result["errcode"])

    def test_get_mass_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.get_mass(201053012)
            self.assertEqual("SEND_SUCCESS", result["msg_status"])

    def test_create_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.create({"button": [{"type": "click", "name": "test", "key": "test"}]})
            self.assertEqual(0, result["errcode"])

    def test_get_menu(self):
        with HTTMock(wechat_api_mock):
            menu = self.client.menu.get()
            self.assertTrue("menu" in menu)

    def test_delete_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.delete()
            self.assertEqual(0, result["errcode"])

    def test_update_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.update({"button": [{"type": "click", "name": "test", "key": "test"}]})
            self.assertEqual(0, result["errcode"])

    def test_short_url(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.short_url("http://www.qq.com")
            self.assertEqual("http://qq.com", result["short_url"])

    def test_get_wechat_ips(self):
        with HTTMock(wechat_api_mock):
            result = self.client.misc.get_wechat_ips()
            self.assertEqual(["127.0.0.1"], result)

    def test_get_user_info(self):
        with HTTMock(wechat_api_mock):
            openid = "o6_bmjrPTlm6_2sgVt7hMZOPfL2M"
            user = self.client.user.get(openid)
            self.assertEqual("Band", user["nickname"])

    def test_get_followers(self):
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_followers()
            self.assertEqual(2, result["total"])
            self.assertEqual(2, result["count"])

    def test_update_user_remark(self):
        with HTTMock(wechat_api_mock):
            openid = "openid"
            remark = "test"
            result = self.client.user.update_remark(openid, remark)
            self.assertEqual(0, result["errcode"])

    def test_get_user_info_batch(self):
        user_list = [
            {"openid": "otvxTs4dckWG7imySrJd6jSi0CWE", "lang": "zh-CN"},
            {"openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg", "lang": "zh-CN"},
        ]
        with HTTMock(wechat_api_mock):
            result = self.client.user.get_batch(user_list)
            self.assertEqual(user_list[0]["openid"], result[0]["openid"])
            self.assertEqual("iWithery", result[0]["nickname"])
            self.assertEqual(user_list[1]["openid"], result[1]["openid"])

    def test_create_qrcode(self):
        data = {"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
        with HTTMock(wechat_api_mock):
            result = self.client.qrcode.create(data)
            self.assertEqual(1800, result["expire_seconds"])

    def test_get_qrcode_url_with_str_ticket(self):
        ticket = "123"
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123", url)

    def test_get_qrcode_url_with_dict_ticket(self):
        ticket = {"ticket": "123"}
        url = self.client.qrcode.get_url(ticket)
        self.assertEqual("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=123", url)

    def test_customservice_add_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.add_account("test1@test", "test1", "test1")
            self.assertEqual(0, result["errcode"])

    def test_customservice_update_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.update_account("test1@test", "test1", "test1")
            self.assertEqual(0, result["errcode"])

    def test_customservice_delete_account(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.delete_account("test1@test")
            self.assertEqual(0, result["errcode"])

    def test_customservice_upload_headimg(self):
        media_file = six.StringIO("nothing")
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.upload_headimg("test1@test", media_file)
            self.assertEqual(0, result["errcode"])

    def test_customservice_get_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_get_online_accounts(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_online_accounts()
            self.assertEqual(2, len(result))

    def test_customservice_create_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.create_session("openid", "test1@test")
            self.assertEqual(0, result["errcode"])

    def test_customservice_close_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.close_session("openid", "test1@test")
            self.assertEqual(0, result["errcode"])

    def test_customservice_get_session(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session("openid")
            self.assertEqual("test1@test", result["kf_account"])

    def test_customservice_get_session_list(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_session_list("test1@test")
            self.assertEqual(2, len(result))

    def test_customservice_get_wait_case(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_wait_case()
            self.assertEqual(150, result["count"])

    def test_customservice_get_records(self):
        with HTTMock(wechat_api_mock):
            result = self.client.customservice.get_records(123456789, 987654321, 1)
            self.assertEqual(2, len(result))

    def test_datacube_get_user_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_summary("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_user_cumulate(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_cumulate(datetime(2014, 12, 6), datetime(2014, 12, 7))
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_interface_summary_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_interface_summary_hour("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_article_summary(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_summary("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_article_total(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_article_total("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_user_read_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_read_hour("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_user_share(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share("2014-12-06", "2014-12-07")
            self.assertEqual(2, len(result))

    def test_datacube_get_user_share_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_user_share_hour("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_hour(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_hour("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_week("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_month("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_week(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_week("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_datacube_get_upstream_msg_dist_month(self):
        with HTTMock(wechat_api_mock):
            result = self.client.datacube.get_upstream_msg_dist_month("2014-12-06", "2014-12-07")
            self.assertEqual(1, len(result))

    def test_jsapi_get_ticket(self):
        with HTTMock(wechat_api_mock):
            result = self.client.jsapi.get_ticket()
            self.assertEqual(
                "bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",  # NOQA
                result["ticket"],
            )
            self.assertEqual(7200, result["expires_in"])

    def test_jsapi_get_jsapi_signature(self):
        noncestr = "Wm3WZYTPz0wzccnW"
        ticket = "sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg"  # NOQA
        timestamp = 1414587457
        url = "http://mp.weixin.qq.com?params=value"
        signature = self.client.jsapi.get_jsapi_signature(noncestr, ticket, timestamp, url)
        self.assertEqual("0f9de62fce790f9a083d5c99e95740ceb90c27ed", signature)

    def test_menu_get_menu_info(self):
        with HTTMock(wechat_api_mock):
            menu_info = self.client.menu.get_menu_info()
            self.assertEqual(1, menu_info["is_menu_open"])

    def test_message_get_autoreply_info(self):
        with HTTMock(wechat_api_mock):
            autoreply = self.client.message.get_autoreply_info()
            self.assertEqual(1, autoreply["is_autoreply_open"])

    def test_shakearound_apply_device_id(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.apply_device_id(1, "test")
            self.assertEqual(123, res["apply_id"])

    def test_shakearound_update_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.update_device("1234", comment="test")
            self.assertEqual(0, res["errcode"])

    def test_shakearound_bind_device_location(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.bind_device_location(123, 1234)
            self.assertEqual(0, res["errcode"])

    def test_shakearound_search_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.search_device(apply_id=123)
            self.assertEqual(151, res["total_count"])
            self.assertEqual(2, len(res["devices"]))

    def test_shakearound_add_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.add_page("test", "test", "http://www.qq.com", "http://www.qq.com")
            self.assertEqual(28840, res["page_id"])

    def test_shakearound_update_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.update_page(123, "test", "test", "http://www.qq.com", "http://www.qq.com")
            self.assertEqual(28840, res["page_id"])

    def test_shakearound_delete_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.delete_page(123)
            self.assertEqual(0, res["errcode"])

    def test_shakearound_search_page(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.search_pages(123)
            self.assertEqual(2, res["total_count"])
            self.assertEqual(2, len(res["pages"]))

    def test_shakearound_add_material(self):
        with HTTMock(wechat_api_mock):
            media_file = six.StringIO("nothing")
            res = self.client.shakearound.add_material(media_file, "icon")
            self.assertEqual(
                "http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120",  # NOQA
                res["pic_url"],
            )

    def test_shakearound_bind_device_pages(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.bind_device_pages(123, 1, 1, 1234)
            self.assertEqual(0, res["errcode"])

    def test_shakearound_get_shake_info(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_shake_info("123456")
            self.assertEqual(14211, res["page_id"])
            self.assertEqual("oVDmXjp7y8aG2AlBuRpMZTb1-cmA", res["openid"])

    def test_shakearound_get_device_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_device_statistics("2015-04-01 00:00:00", "2015-04-17 00:00:00", 1234)
            self.assertEqual(2, len(res))

    def test_shakearound_get_page_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_page_statistics("2015-04-01 00:00:00", "2015-04-17 00:00:00", 1234)
            self.assertEqual(2, len(res))

    def test_material_get_count(self):
        with HTTMock(wechat_api_mock):
            res = self.client.material.get_count()
            self.assertEqual(1, res["voice_count"])
            self.assertEqual(2, res["video_count"])
            self.assertEqual(3, res["image_count"])
            self.assertEqual(4, res["news_count"])

    def test_shakearound_get_apply_status(self):
        with HTTMock(wechat_api_mock):
            res = self.client.shakearound.get_apply_status(1234)
            self.assertEqual(4, len(res))

    def test_reraise_requests_exception(self):
        @urlmatch(netloc=r"(.*\.)?api\.weixin\.qq\.com$")
        def _wechat_api_mock(url, request):
            return {"status_code": 404, "content": "404 not found"}

        try:
            with HTTMock(_wechat_api_mock):
                self.client.material.get_count()
        except WeChatClientException as e:
            self.assertEqual(404, e.response.status_code)

    def test_wifi_list_shops(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.list_shops()
            self.assertEqual(16, res["totalcount"])
            self.assertEqual(1, res["pageindex"])

    def test_wifi_add_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.add_device(123, "WX-test", "12345678", "00:1f:7a:ad:5c:a8")
            self.assertEqual(0, res["errcode"])

    def test_wifi_list_devices(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.list_devices()
            self.assertEqual(2, res["totalcount"])
            self.assertEqual(1, res["pageindex"])

    def test_wifi_delete_device(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.delete_device("00:1f:7a:ad:5c:a8")
            self.assertEqual(0, res["errcode"])

    def test_wifi_get_qrcode_url(self):
        with HTTMock(wechat_api_mock):
            qrcode_url = self.client.wifi.get_qrcode_url(123, 0)
            self.assertEqual("http://www.qq.com", qrcode_url)

    def test_wifi_set_homepage(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.set_homepage(123, 0)
            self.assertEqual(0, res["errcode"])

    def test_wifi_get_homepage(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.get_homepage(429620)
            self.assertEqual(1, res["template_id"])
            self.assertEqual("http://wifi.weixin.qq.com/", res["url"])

    def test_wifi_list_statistics(self):
        with HTTMock(wechat_api_mock):
            res = self.client.wifi.list_statistics("2015-05-01", "2015-05-02")
            self.assertEqual(2, len(res))

    def test_upload_mass_image(self):
        media_file = six.StringIO("nothing")
        with HTTMock(wechat_api_mock):
            res = self.client.media.upload_mass_image(media_file)
        self.assertEqual(
            "http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYs CNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0",  # NOQA
            res,
        )
Esempio n. 40
0
 def setUp(self):
     self.client = WeChatClient(self.app_id, self.secret)
Esempio n. 41
0
class WeChatClientTestCase(unittest.TestCase):

    app_id = '123456'
    secret = '123456'

    def setUp(self):
        self.client = WeChatClient(self.app_id, self.secret)

    def test_fetch_access_token(self):
        with HTTMock(wechat_api_mock):
            token = self.client.fetch_access_token()
            self.assertEqual('1234567890', token['access_token'])
            self.assertEqual(7200, token['expires_in'])
            self.assertEqual('1234567890', self.client.access_token)

    def test_upload_media(self):
        media_file = six.StringIO('nothing')
        with HTTMock(wechat_api_mock):
            media = self.client.media.upload('image', media_file)
            self.assertEqual('image', media['type'])
            self.assertEqual('12345678', media['media_id'])

    def test_create_group(self):
        with HTTMock(wechat_api_mock):
            group = self.client.group.create('test')
            self.assertEqual(1, group['group']['id'])
            self.assertEqual('test', group['group']['name'])

    def test_send_text_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_text(1, 'test')
            self.assertEqual(0, result['errcode'])

    def test_send_image_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_image(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_voice_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_voice(1, '123456')
            self.assertEqual(0, result['errcode'])

    def test_send_video_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_video(
                1, '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_music_message(self):
        with HTTMock(wechat_api_mock):
            result = self.client.message.send_music(
                1, 'http://www.qq.com', 'http://www.qq.com',
                '123456', 'test', 'test'
            )
            self.assertEqual(0, result['errcode'])

    def test_send_articles_message(self):
        with HTTMock(wechat_api_mock):
            articles = [{
                'title': 'test',
                'description': 'test',
                'url': 'http://www.qq.com',
                'image': 'http://www.qq.com'
            }]
            result = self.client.message.send_articles(1, articles)
            self.assertEqual(0, result['errcode'])

    def test_create_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.create({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])

    def test_get_menu(self):
        with HTTMock(wechat_api_mock):
            menu = self.client.menu.get()
            self.assertTrue('menu' in menu)

    def test_delete_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.delete()
            self.assertEqual(0, result['errcode'])

    def test_update_menu(self):
        with HTTMock(wechat_api_mock):
            result = self.client.menu.update({
                'button': [
                    {
                        'type': 'click',
                        'name': 'test',
                        'key': 'test'
                    }
                ]
            })
            self.assertEqual(0, result['errcode'])