douyong1285 2016-07-25 16:36
浏览 32
已采纳

模拟加密/ SSH /终端

Has anyone had any success or have any ideas on what would be the best way to mock entry (for testing purposes) to a term.ReadPassword(int(os.Stdin.Fd())) call in the golang.org/x/crypto/ssh/terminal package?

I have tried creating a temp file (vs os.Stdin) and writing string values like testing or testing to the temp file but I get the error inappropriate ioctl for device. I'm guessing it is something TTY related or a specific format that is missing(?) but I really am not sure.

Help appreciated.

  • 写回答

2条回答 默认 最新

  • duanjie2701 2016-07-26 07:00
    关注

    If you are stubbing this test by creating a fake file that os.Stdin is referencing, your tests will become tremendously OS specific when you try to handle ReadPassword(). This is because under the hood Go is compiling separate syscalls depending on the OS. ReadPassword() is implemented here, but the syscalls based on architecture and OS are in this directory. As you can see there are many. I cannot think of a good way to stub this test in the way you are specifying.

    With the limited understanding of your problem the solution I would propose would be to inject a simple interface along the lines of:

    type PasswordReader interface {
        ReadPassword(fd int) ([]byte, error)
    }
    
    func (pr PasswordReader) ReadPassword(fd int) ([]byte, error) {
        return terminal.ReadPassword(fd)
    }
    

    This way you can pass in a fake object to your tests, and stub the response to ReadPassword. I know this feels like writing your code for your tests, but you can reframe this thought as terminal is an outside dependency (I/O) that should be injected! So now your tests are not only ensuring your code works, but actually helping you make good design decisions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号