سؤال

I have to test the function where it calls wp_get_attachment_image_src. How do I add an image for testing, because right now if I call this method it returns false.

هل كانت مفيدة؟

المحلول

I'd take a look at how WordPress has constructed their attachment tests. You'll find that tests/phpunit/tests/post/attachments.php they use this method:

function _make_attachment( $upload, $parent_post_id = 0 ) {

    $type = '';
    if ( !empty($upload['type']) ) {
        $type = $upload['type'];
    } else {
        $mime = wp_check_filetype( $upload['file'] );
        if ($mime)
            $type = $mime['type'];
    }

    $attachment = array(
        'post_title' => basename( $upload['file'] ),
        'post_content' => '',
        'post_type' => 'attachment',
        'post_parent' => $parent_post_id,
        'post_mime_type' => $type,
        'guid' => $upload[ 'url' ],
    );

    // Save the data
    $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $parent_post_id );
    wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );

    return $this->ids[] = $id;

}

They've also included sample images with their tests. Here is an example of how they call the _make_attachment() method in one of their tests:

function test_insert_image_no_thumb() {

    // this image is smaller than the thumbnail size so it won't have one
    $filename = ( DIR_TESTDATA.'/images/test-image.jpg' );
    $contents = file_get_contents($filename);

    $upload = wp_upload_bits(basename($filename), null, $contents);
    $this->assertTrue( empty($upload['error']) );

    $id = $this->_make_attachment($upload);

    // ...

So you should be able to use something like that to upload an image for your test. You could supply the image to use yourself, or just use one of those already included.

نصائح أخرى

If you're using the WordPress testing suite (your test classes extend WP_UnitTestCase), you can use the included factory.

I.e. if your tests are in a tests directory you could create tests/assets/dummy-attachment.jpg

$post = $this->factory->post->create_and_get();
$attachment_id = $this->factory->attachment->create_upload_object( __DIR__ . '/assets/dummy-attachment.jpg', $post->ID );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى wordpress.stackexchange
scroll top