🌑

Hi there.

Copilot 使用感受

听闻 GitHub 上有一个非常好的项目,叫做 Copilot,它是一个自动化测试工具,可以自动生成测试用例,并且可以自动运行测试用例。*

但是,该项目仍处于内测中,于是火速申请了一份。

很快,GitHub 就接受了我的申请:

image.png

在接下来的例子中,我们将使用 Copilot 生成测试用例,并运行测试用例。*

假设:我们通过 pid (Pixiv作品id)使用我个人搭建的服务获取该pid下的所有信息,语言为 Python。

  • 创建copilot_example.py

  • 在第一行键入# Get illust info from Pixiv by pid use api.kyomotoi.moe

  • 得到以下结果:

    def get_illust(pid):
        import requests
        import json
        url = 'https://api.kyomotoi.moe/pixiv/illust/' + pid
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}
        r = requests.get(url, headers=headers)
        r.encoding = 'utf-8'
        data = json.loads(r.text)
        return data

    url好像不正确,让我们给他替换为:https://api.kyomotoi.moe/api/pixiv/illust?id=

    如果不喜欢这段代码,我们还可以通过Ctrl+Enter

  • 让我们传入pid:83996011,并让其输出内容

    result = get_illust("83996011")
    print(result)
  • 检查结果:

    image.png

    返回包含我们所需的所有信息 *

  • 让我们给 Copilot 提升一些难度:将这段同步运行的代码改为异步!

  • 删除旧的示例,在第一行键入# Get illust info from Pixiv by pid use api.kyomotoi.moe and aiohttp

  • 得到以下结果:

    async def get_illust(pid):
        async with aiohttp.ClientSession() as session:
            async with session.get(f"https://api.kyomotoi.moe/illust/{pid}") as resp:
                return await resp.json()

    看起来更加简洁了,但是问题也随之而来:

    • 依赖未导入:aiohttp,让我们帮它导入
    • url依然不正确,让我们给他替换为:https://api.kyomotoi.moe/api/pixiv/illust?id={pid}
  • 传入之前的参数,通过asyncio运行它

    async def main():
        pid = "83996011"
        result = await get_illust(pid)
        print(result)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
  • 得到如下结果:
    image.png

    返回包含我们所需的所有信息 *


让我们换一种语言,用golang

这次,我们来生成一个小工具。

  • 创建copilot_example.go

  • 在第一行键入// Judge string whether is in array

  • 得到以下结果:

    func Judge(str string, array []string) bool {
        for _, v := range array {
            if v == str {
                return true
            }
        }
        return false
    }
  • 测试:

    func main() {
        fmt.Println(Judge("hello", []string{"hello", "world"}))
    }

    输出:true

  • 总结:

    • 轻度减少开发时间,让我们更加专注于程序本身。*
    • Copilot 很强,但它不是万能的,终究只是一个工具。
    • 由于使用了公开的仓库(GitHub public repo)作为训练集,所以生成的代码可能会包含协议问题。
    • Copilot 还有很长一段路要走。

不知道读者是否发现,本文部分句子后带符号为 * 的是由 Copilot 生成的

— Aug 18, 2021

Made with ❤ by Kyomotoi.