HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/ste.komma.pro/tests/Unit/SitemapUrlAvailablilityTest.php
<?php

namespace Tests\Unit;

use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;
use Tests\TestCase;

/**
 * Class SitemapUrlAvailablilityTest
 *
 * Tests if the url's in the sitemap are available
 *
 * @package Tests\Unit
 */
class SitemapUrlAvailablilityTest extends TestCase
{
    /**
     * @group SitemapUrlAvailabilityTest
     * @test
     * @throws \Exception
     */
    public function testAvailability()
    {
        $client = new Client();
        try {
            $response = $client->get(url('/sitemap.xml'));
        } catch (\Exception $exception) {
            $this->fail('Error: Application not available on "'.url('/').'". Did you forgot to run php artisan serve --env=testing?');
        }
        $this->assertEquals(200, $response->getStatusCode(), 'Error: Make sure php artisan serve --env=testing is running');

        $crawler = new Crawler($response->getBody()->getContents());

        $crawler->filter('[href]')->each(function(Crawler $node ) use($client) {
            $link = $node->attr('href');

//            echo 'Checking sitemap link: '.$link.PHP_EOL;
            try {
                $response = $client->head($link); //We do a head request since that will not get the content and laravel will not be picky about the request method (E.g If should you use post, put, patch etc)
                $statusCode = $response->getStatusCode();
                if($statusCode !== 200) $this->fail('The link "'.$link.'" was not available (No status 200 code given). Status code was '.$statusCode);
            } catch (\Exception $exception) {
                $this->fail($exception->getMessage());
            }

        });
    }
}