28
28
use MongoDB \Laravel \Tests \Models \Soft ;
29
29
use MongoDB \Laravel \Tests \Models \SqlUser ;
30
30
use MongoDB \Laravel \Tests \Models \User ;
31
+ use PHPUnit \Framework \Attributes \TestWith ;
31
32
32
33
use function abs ;
33
34
use function array_keys ;
@@ -46,6 +47,7 @@ class ModelTest extends TestCase
46
47
{
47
48
public function tearDown (): void
48
49
{
50
+ Carbon::setTestNow ();
49
51
User::truncate ();
50
52
Soft::truncate ();
51
53
Book::truncate ();
@@ -1100,4 +1102,53 @@ public function testCreateOrFirstRequiresFilter()
1100
1102
$ this ->expectExceptionMessage ('You must provide attributes to check for duplicates ' );
1101
1103
User::createOrFirst ([]);
1102
1104
}
1105
+
1106
+ #[TestWith([['_id ' => new ObjectID ()]])]
1107
+ #[TestWith([['foo ' => 'bar ' ]])]
1108
+ public function testUpdateOrCreate (array $ criteria )
1109
+ {
1110
+ // Insert data to ensure we filter on the correct criteria, and not getting
1111
+ // the first document randomly.
1112
+ User::insert ([
1113
+
1114
+
1115
+ ]);
1116
+
1117
+ Carbon::setTestNow ('2010-01-01 ' );
1118
+ $ createdAt = Carbon::now ()->getTimestamp ();
1119
+
1120
+ // Create
1121
+ $ user = User::updateOrCreate (
1122
+ $ criteria ,
1123
+ [
'email ' =>
'[email protected] ' ,
'birthday ' =>
new DateTime (
'1987-05-28 ' )],
1124
+ );
1125
+ $ this ->assertInstanceOf (User::class, $ user );
1126
+ $ this ->
assertEquals (
'[email protected] ' ,
$ user->
email );
1127
+ $ this ->assertEquals (new DateTime ('1987-05-28 ' ), $ user ->birthday );
1128
+ $ this ->assertEquals ($ createdAt , $ user ->created_at ->getTimestamp ());
1129
+ $ this ->assertEquals ($ createdAt , $ user ->updated_at ->getTimestamp ());
1130
+
1131
+ Carbon::setTestNow ('2010-02-01 ' );
1132
+ $ updatedAt = Carbon::now ()->getTimestamp ();
1133
+
1134
+ // Update
1135
+ $ user = User::updateOrCreate (
1136
+ $ criteria ,
1137
+ ['birthday ' => new DateTime ('1990-01-12 ' ), 'foo ' => 'bar ' ],
1138
+ );
1139
+
1140
+ $ this ->assertInstanceOf (User::class, $ user );
1141
+ $ this ->
assertEquals (
'[email protected] ' ,
$ user->
email );
1142
+ $ this ->assertEquals (new DateTime ('1990-01-12 ' ), $ user ->birthday );
1143
+ $ this ->assertEquals ($ createdAt , $ user ->created_at ->getTimestamp ());
1144
+ $ this ->assertEquals ($ updatedAt , $ user ->updated_at ->getTimestamp ());
1145
+
1146
+ // Stored data
1147
+ $ checkUser = User::where ($ criteria )->first ();
1148
+ $ this ->assertInstanceOf (User::class, $ checkUser );
1149
+ $ this ->
assertEquals (
'[email protected] ' ,
$ checkUser->
email );
1150
+ $ this ->assertEquals (new DateTime ('1990-01-12 ' ), $ checkUser ->birthday );
1151
+ $ this ->assertEquals ($ createdAt , $ checkUser ->created_at ->getTimestamp ());
1152
+ $ this ->assertEquals ($ updatedAt , $ checkUser ->updated_at ->getTimestamp ());
1153
+ }
1103
1154
}
0 commit comments