douchuifk90315 2012-07-01 08:17
浏览 34
已采纳

如何模拟内置的php套接字函数?

I'm working on some code that reads from a socket, and it goes wrong when it gets a certain large input. I went to add a unit test for this, before fixing it, but got stuck because I cannot mock fread (and the other PHP built-in functions I'm using such as fsockopen, feof, etc.).

In simple terms my problem is that this code fails with "Fatal error: Cannot redeclare fgets() ...":

function fgets($fp){
return "xxx";
}

I realize I could create a socket wrapper class, that my real code uses, and then I could create a mock object for that wrapper class. But that is The Tail Wagging The Dog, and I can think of reasons it is a bad idea, beyond just the principle of the thing. (E.g. Making code more complex, efficiency, having to refactor code not under test yet.)

So, my question is how can I replace the built-in fgets() implementation with my own, within a unit test? (Or, if you want to think outside the box, the question can be phrased as: how can I control the string that a call to fgets($socket) returns, when $socket is the return value from a call to fsockopen?)


ASIDE

Installing apd, as required by the correct answer, is hard work; it was last released in 2004, and does not support php 5.3 out of the box. No Ubuntu package for it and also pecl install apd failed. So here are the procedures to install it (these are for ubuntu 10.04) (all done as root):

pecl download apd
tar xzf apd-1.0.1.tgz
cd apd-1.0.1
phpize
./configure
# Do edits (see below)
make install

See https://bugs.php.net/bug.php?id=58798 for the patch you need to do. NB. there is only one line you really have to change, so you can do it by hand, as follows: open php_apd.c in a text editor, go to line 967, and replace the CG(extended_info) = 1 line with this one:

CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;

Finally, you need to add a php.ini entry to activate it. See http://php.net/manual/en/apd.installation.php

  • 写回答

4条回答 默认 最新

  • dongyi0210 2012-07-05 09:09
    关注

    If you don't have access to APD or Runkit but are using namespaces, try this: https://stackoverflow.com/a/5337635/664108 (Answer in link refers to time() but it makes no difference)

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

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)