nur-sery/nur_tests/io/csv/CsvWriterTest.php

117 lines
3.1 KiB
PHP
Raw Normal View History

2023-12-03 22:11:29 +04:00
<?php
namespace nur\io\csv;
use nur\b\io\StringWriter;
use nur\t\TestCase;
class CsvWriterTest extends TestCase {
function testWriter() {
$w = new StringWriter();
$writer = new CsvWriter($w);
$writer->writeAll([
["nom" => "clain", "prenom" => "jephté", "age" => 45],
["nom" => "enpion", "prenom" => "tarte", "age" => 36],
["nom" => "cool", "prenom" => "plusieurs
lignes", "age" => 15],
]);
self::assertSame("nom,prenom,age
clain,jephté,45
enpion,tarte,36
cool,\"plusieurs
lignes\",15
", $w->getString());
}
function testResource() {
$w = fopen("php://memory", "w+b");
$writer = new CsvWriter($w);
$writer->writeAll([
["nom" => "clain", "prenom" => "jephté", "age" => 45],
["nom" => "enpion", "prenom" => "tarte", "age" => 36],
["nom" => "cool", "prenom" => "plusieurs
lignes", "age" => 15],
]);
rewind($w);
self::assertSame("nom,prenom,age
clain,jephté,45
enpion,tarte,36
cool,\"plusieurs
lignes\",15
", stream_get_contents($w));
}
function testEmpty() {
$w = new StringWriter();
$writer = new CsvWriter($w);
$writer->writeAll([]);
self::assertSame("", $w->getString());
$w = new StringWriter();
$writer = new CsvWriter($w);
$writer->setHeaders(["nom", "prenom", "age"]);
$writer->writeAll([]);
self::assertSame("nom,prenom,age\n", $w->getString());
}
function testMappings() {
$rows = [
["nom" => "clain", "prenom" => "jephte", "annees" => "45", "ville" => "sainte-clotilde"],
["nom" => "enpion", "prenom" => "tarte", "annees" => "36", "ville" => "missile fixe"],
];
###########################################################################
## mappings au format chaine
# tester includes + excludes + remap
# ordre du mapping
$w = new StringWriter();
$writer = new CsvWriter($w, [
"header_mappings" => "=prenom,annees=age,nom",
]);
$writer->writeAll($rows);
self::assertSame("prenom,age,nom
,45,clain
,36,enpion
", $w->getString());
# tester excludes + remap
# ordre de la source
$w = new StringWriter();
$writer = new CsvWriter($w, [
"header_mappings" => "=prenom,annees=age",
]);
$writer->writeAll($rows);
self::assertSame("nom,prenom,age,ville
clain,,45,sainte-clotilde
enpion,,36,\"missile fixe\"
", $w->getString());
###########################################################################
## mappings au format tableau
# tester includes + excludes + remap
# ordre du mapping
$w = new StringWriter();
$writer = new CsvWriter($w, [
"header_mappings" => ["prenom" => null, "annees" => "age", "nom"],
]);
$writer->writeAll($rows);
self::assertSame("prenom,age,nom
,45,clain
,36,enpion
", $w->getString());
# tester excludes + remap
# ordre de la source
$w = new StringWriter();
$writer = new CsvWriter($w, [
"header_mappings" => ["prenom" => null, "annees" => "age"],
]);
$writer->writeAll($rows);
self::assertSame("nom,prenom,age,ville
clain,,45,sainte-clotilde
enpion,,36,\"missile fixe\"
", $w->getString());
}
}