EnvTest.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace think\tests;
  3. use org\bovigo\vfs\vfsStream;
  4. use PHPUnit\Framework\TestCase;
  5. use think\Env;
  6. use think\Exception;
  7. class EnvTest extends TestCase
  8. {
  9. public function testEnvFile()
  10. {
  11. $root = vfsStream::setup();
  12. $envFile = vfsStream::newFile('.env')->setContent("key1=value1\nkey2=value2");
  13. $root->addChild($envFile);
  14. $env = new Env();
  15. $env->load($envFile->url());
  16. $this->assertEquals('value1', $env->get('key1'));
  17. $this->assertEquals('value2', $env->get('key2'));
  18. $this->assertSame(['KEY1' => 'value1', 'KEY2' => 'value2'], $env->get());
  19. }
  20. public function testServerEnv()
  21. {
  22. $env = new Env();
  23. $this->assertEquals('value2', $env->get('key2', 'value2'));
  24. putenv('PHP_KEY7=value7');
  25. putenv('PHP_KEY8=false');
  26. putenv('PHP_KEY9=true');
  27. $this->assertEquals('value7', $env->get('key7'));
  28. $this->assertFalse($env->get('KEY8'));
  29. $this->assertTrue($env->get('key9'));
  30. }
  31. public function testSetEnv()
  32. {
  33. $env = new Env();
  34. $env->set([
  35. 'key1' => 'value1',
  36. 'key2' => [
  37. 'key1' => 'value1-2',
  38. ],
  39. ]);
  40. $env->set('key3', 'value3');
  41. $env->key4 = 'value4';
  42. $env['key5'] = 'value5';
  43. $this->assertEquals('value1', $env->get('key1'));
  44. $this->assertEquals('value1-2', $env->get('key2.key1'));
  45. $this->assertEquals('value3', $env->get('key3'));
  46. $this->assertEquals('value4', $env->key4);
  47. $this->assertEquals('value5', $env['key5']);
  48. $this->expectException(Exception::class);
  49. unset($env['key5']);
  50. }
  51. public function testHasEnv()
  52. {
  53. $env = new Env();
  54. $env->set(['foo' => 'bar']);
  55. $this->assertTrue($env->has('foo'));
  56. $this->assertTrue(isset($env->foo));
  57. $this->assertTrue($env->offsetExists('foo'));
  58. }
  59. }