diff options
| author | Alex Gleason <alex@alexgleason.me> | 2021-04-30 13:17:03 -0500 | 
|---|---|---|
| committer | Alex Gleason <alex@alexgleason.me> | 2021-04-30 13:17:03 -0500 | 
| commit | 52fc59f125c10ad73b9fd1a0639b6dc5681776ca (patch) | |
| tree | 7de32329acbdd4bdf5c753678a2d459c61b58d80 /test | |
| parent | a8fa00ef666f574aec8048626aed78a7d62e6915 (diff) | |
| parent | 377f84f3678f9c2541fbd4a200cd93c5ab0dea24 (diff) | |
| download | pleroma-52fc59f125c10ad73b9fd1a0639b6dc5681776ca.tar.gz pleroma-52fc59f125c10ad73b9fd1a0639b6dc5681776ca.zip  | |
Merge remote-tracking branch 'upstream/develop' into earmark
Diffstat (limited to 'test')
378 files changed, 6908 insertions, 2684 deletions
diff --git a/test/config/emoji.txt b/test/config/emoji.txt new file mode 100644 index 000000000..14dd0c332 --- /dev/null +++ b/test/config/emoji.txt @@ -0,0 +1 @@ +external_emoji, https://example.com/emoji.png diff --git a/test/credo/check/consistency/file_location.ex b/test/credo/check/consistency/file_location.ex index 500983608..abc55fffc 100644 --- a/test/credo/check/consistency/file_location.ex +++ b/test/credo/check/consistency/file_location.ex @@ -1,7 +1,7 @@  # Pleroma: A lightweight social networking server  # Originally taken from  # https://github.com/VeryBigThings/elixir_common/blob/master/lib/vbt/credo/check/consistency/file_location.ex -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Credo.Check.Consistency.FileLocation do diff --git a/test/fixtures/bridgy/actor.json b/test/fixtures/bridgy/actor.json new file mode 100644 index 000000000..5b2d8982b --- /dev/null +++ b/test/fixtures/bridgy/actor.json @@ -0,0 +1,80 @@ +{ +  "id": "https://fed.brid.gy/jk.nipponalba.scot", +  "url": "https://fed.brid.gy/r/https://jk.nipponalba.scot", +  "urls": [ +    { +      "value": "https://jk.nipponalba.scot" +    }, +    { +      "value": "https://social.nipponalba.scot/jk" +    }, +    { +      "value": "https://px.nipponalba.scot/jk" +    } +  ], +  "@context": "https://www.w3.org/ns/activitystreams", +  "type": "Person", +  "name": "J K 🇯🇵🏴", +  "image": [ +    { +      "url": "https://jk.nipponalba.scot/images/profile.jpg", +      "type": "Image", +      "name": "profile picture" +    } +  ], +  "tag": [ +    { +      "type": "Tag", +      "name": "Craft Beer" +    }, +    { +      "type": "Tag", +      "name": "Single Malt Whisky" +    }, +    { +      "type": "Tag", +      "name": "Homebrewing" +    }, +    { +      "type": "Tag", +      "name": "Scottish Politics" +    }, +    { +      "type": "Tag", +      "name": "Scottish History" +    }, +    { +      "type": "Tag", +      "name": "Japanese History" +    }, +    { +      "type": "Tag", +      "name": "Tech" +    }, +    { +      "type": "Tag", +      "name": "Veganism" +    }, +    { +      "type": "Tag", +      "name": "Cooking" +    } +  ], +  "icon": [ +    { +      "url": "https://jk.nipponalba.scot/images/profile.jpg", +      "type": "Image", +      "name": "profile picture" +    } +  ], +  "preferredUsername": "jk.nipponalba.scot", +  "summary": "", +  "publicKey": { +    "id": "jk.nipponalba.scot", +    "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdarxwzxnNbJ2hneWOYHkYJowk\npyigQtxlUd0VjgSQHwxU9kWqfbrHBVADyTtcqi/4dAzQd3UnCI1TPNnn4LPZY9PW\noiWd3Zl1/EfLFxO7LU9GS7fcSLQkyj5JNhSlN3I8QPudZbybrgRDVZYooDe1D+52\n5KLGqC2ajrIVOiDRTQIDAQAB\n-----END PUBLIC KEY-----" +  }, +  "inbox": "https://fed.brid.gy/jk.nipponalba.scot/inbox", +  "outbox": "https://fed.brid.gy/jk.nipponalba.scot/outbox", +  "following": "https://fed.brid.gy/jk.nipponalba.scot/following", +  "followers": "https://fed.brid.gy/jk.nipponalba.scot/followers" +} diff --git a/test/fixtures/config/temp.exported_from_db.secret.exs b/test/fixtures/config/temp.exported_from_db.secret.exs new file mode 100644 index 000000000..64bee7f32 --- /dev/null +++ b/test/fixtures/config/temp.exported_from_db.secret.exs @@ -0,0 +1,5 @@ +use Mix.Config + +config :pleroma, exported_config_merged: true + +config :pleroma, :first_setting, key: "new value" diff --git a/test/fixtures/config/temp.secret.exs b/test/fixtures/config/temp.secret.exs index 621bc8cf6..4b3af39ec 100644 --- a/test/fixtures/config/temp.secret.exs +++ b/test/fixtures/config/temp.secret.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  use Mix.Config diff --git a/test/fixtures/guppe-actor.json b/test/fixtures/guppe-actor.json new file mode 100644 index 000000000..d5829ee1f --- /dev/null +++ b/test/fixtures/guppe-actor.json @@ -0,0 +1,26 @@ +{ +   "@context" : [ +      "https://www.w3.org/ns/activitystreams", +      "https://w3id.org/security/v1" +   ], +   "followers" : "https://gup.pe/u/bernie2020/followers", +   "following" : "https://gup.pe/u/bernie2020/following", +   "icon" : { +      "mediaType" : "image/jpeg", +      "type" : "Image", +      "url" : "https://gup.pe/f/guppe.png" +   }, +   "id" : "https://gup.pe/u/bernie2020", +   "inbox" : "https://gup.pe/u/bernie2020/inbox", +   "liked" : "https://gup.pe/u/bernie2020/liked", +   "name" : "Bernie2020 group", +   "outbox" : "https://gup.pe/u/bernie2020/outbox", +   "preferredUsername" : "Bernie2020", +   "publicKey" : { +      "id" : "https://gup.pe/u/bernie2020#main-key", +      "owner" : "https://gup.pe/u/bernie2020", +      "publicKeyPem" : "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAw4J8nSrdWWxFaipgWDhR\nbTFzHUGoFy7Gjdc6gg9ZWGWDm9ZU5Ct0C/4o72dXSWdyLbQGYMbWVHLI1LHWKSiC\nVtwIYoccQBaxfi5bCxsahWhhSNPfK8tVlySHvBy73ir8KUZm93eAYh1iE9x+Dk63\nInmi7wzjsqHSlu1KxPGYcnyxs+xxhlTUSd5LsPfO1b9sHMW+X4rEky7OC90veCdD\nsoHU+nCmf+2zJSlOrU7DAzqB4Axc9oS9Q5RlT3yARJQMeu6JyjJJP9CMbpGFbUNT\n5Gsw0km1Rc1rR4tUoz8pLUYtliEUK+/0EmHi2EHAT1ueEfMoGGbCaX/mCoMmAwYJ\nwIGYXmKn2/ARIJpw2XPmrKWXqa2AndOQdb3l44Sl3ej2rC/JQmimGCn7tbfKEZyC\n6mMkOYTIeBtyW/wXFc1+GzJxtvA3C9HjilE+O/7gLHfCLP6FRIxg/9kOLhEj64Ed\n5HZ3sylvifXXubS/lLZr6sZW6d9ICoYLZpFw9AoF2zaYWpvJqBrWinnCJzvbMCYj\nfq/RAkcQYSxkDOHquiGgbRZHGAMKLnz5fMKJIzBtdQojYCUmB14OArW+ITUE9i2a\nPAJaXEGZ+BHYp/0ScFaXwp5LIgT1S+sPKxWJU//77wQfs25i7NZHSN/jtXVmsFS6\nLFVw49LcWAz3J2Im+A+uSd8CAwEAAQ==\n-----END PUBLIC KEY-----\n" +   }, +   "summary" : "I'm a group about Bernie2020. Follow me to get all the group posts. Tag me to share with the group. Create other groups by searching for or tagging @yourGroupName@gup.pe", +   "type" : "Group" +} diff --git a/test/fixtures/mastodon/collections/featured.json b/test/fixtures/mastodon/collections/featured.json new file mode 100644 index 000000000..56f8f56fa --- /dev/null +++ b/test/fixtures/mastodon/collections/featured.json @@ -0,0 +1,39 @@ +{ +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    "https://{{domain}}/schemas/litepub-0.1.jsonld", +    { +      "@language": "und" +    } +  ], +  "id": "https://{{domain}}/users/{{nickname}}/collections/featured", +  "orderedItems": [ +    { +      "@context": [ +        "https://www.w3.org/ns/activitystreams", +        "https://{{domain}}/schemas/litepub-0.1.jsonld", +        { +          "@language": "und" +        } +      ], +      "actor": "https://{{domain}}/users/{{nickname}}", +      "attachment": [], +      "attributedTo": "https://{{domain}}/users/{{nickname}}", +      "cc": [ +        "https://{{domain}}/users/{{nickname}}/followers" +      ], +      "content": "", +      "id": "https://{{domain}}/objects/{{object_id}}", +      "published": "2021-02-12T15:13:43.915429Z", +      "sensitive": false, +      "source": "", +      "summary": "", +      "tag": [], +      "to": [ +        "https://www.w3.org/ns/activitystreams#Public" +      ], +      "type": "Note" +    } +  ], +  "type": "OrderedCollection" +} diff --git a/test/fixtures/modules/runtime_module.ex b/test/fixtures/modules/runtime_module.ex index e348c499e..940b58a1b 100644 --- a/test/fixtures/modules/runtime_module.ex +++ b/test/fixtures/modules/runtime_module.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Fixtures.Modules.RuntimeModule do diff --git a/test/fixtures/peertube/actor-person.json b/test/fixtures/peertube/actor-person.json new file mode 100644 index 000000000..8c387d455 --- /dev/null +++ b/test/fixtures/peertube/actor-person.json @@ -0,0 +1,121 @@ +{ +  "type": "Person", +  "id": "https://peertube.stream/accounts/createurs", +  "following": "https://peertube.stream/accounts/createurs/following", +  "followers": "https://peertube.stream/accounts/createurs/followers", +  "playlists": "https://peertube.stream/accounts/createurs/playlists", +  "inbox": "https://peertube.stream/accounts/createurs/inbox", +  "outbox": "https://peertube.stream/accounts/createurs/outbox", +  "preferredUsername": "createurs", +  "url": "https://peertube.stream/accounts/createurs", +  "name": "Créateurs", +  "endpoints": { +    "sharedInbox": "https://peertube.stream/inbox" +  }, +  "publicKey": { +    "id": "https://peertube.stream/accounts/createurs#main-key", +    "owner": "https://peertube.stream/accounts/createurs", +    "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxqkQhbRYbA81+WTYjorR\n2lEMad3kYCnzDjGTLr4I92eanzFHxyELGnjzP6TpEvjOiB9NrCRrqU/iFPLdgrq2\nwIFcXPWdCq6Gcg7QLlaeMM0JoJmr0KTEhzg0XKCo96UsyTzaF4DISxqi8RyoyWeU\nEkgiOzlkdYTlouq3MlQH+p1PBAsNUQfIEUsU+l6k1vzbm8JRwlT+D1bNde4I/Lqs\n4uB5ru3zzInwZ2hz9+heiriNoGEBv74rZHYn966tZVX8iMGx2+m6okozEdEQbqCl\n0ekqDcd8P6CoFqqeeu8coh82OUtuFI/XsbetdWA55YQmSHyMiTsIwVbeoogIETbI\n4QIDAQAB\n-----END PUBLIC KEY-----" +  }, +  "icon": { +    "type": "Image", +    "mediaType": "image/png", +    "url": "https://peertube.stream/lazy-static/avatars/c27b672d-ad8f-498a-adbe-553af8da56f9.png" +  }, +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    "https://w3id.org/security/v1", +    { +      "RsaSignature2017": "https://w3id.org/security#RsaSignature2017" +    }, +    { +      "pt": "https://joinpeertube.org/ns#", +      "sc": "http://schema.org#", +      "Hashtag": "as:Hashtag", +      "uuid": "sc:identifier", +      "category": "sc:category", +      "licence": "sc:license", +      "subtitleLanguage": "sc:subtitleLanguage", +      "sensitive": "as:sensitive", +      "language": "sc:inLanguage", +      "isLiveBroadcast": "sc:isLiveBroadcast", +      "liveSaveReplay": { +        "@type": "sc:Boolean", +        "@id": "pt:liveSaveReplay" +      }, +      "permanentLive": { +        "@type": "sc:Boolean", +        "@id": "pt:permanentLive" +      }, +      "Infohash": "pt:Infohash", +      "Playlist": "pt:Playlist", +      "PlaylistElement": "pt:PlaylistElement", +      "originallyPublishedAt": "sc:datePublished", +      "views": { +        "@type": "sc:Number", +        "@id": "pt:views" +      }, +      "state": { +        "@type": "sc:Number", +        "@id": "pt:state" +      }, +      "size": { +        "@type": "sc:Number", +        "@id": "pt:size" +      }, +      "fps": { +        "@type": "sc:Number", +        "@id": "pt:fps" +      }, +      "startTimestamp": { +        "@type": "sc:Number", +        "@id": "pt:startTimestamp" +      }, +      "stopTimestamp": { +        "@type": "sc:Number", +        "@id": "pt:stopTimestamp" +      }, +      "position": { +        "@type": "sc:Number", +        "@id": "pt:position" +      }, +      "commentsEnabled": { +        "@type": "sc:Boolean", +        "@id": "pt:commentsEnabled" +      }, +      "downloadEnabled": { +        "@type": "sc:Boolean", +        "@id": "pt:downloadEnabled" +      }, +      "waitTranscoding": { +        "@type": "sc:Boolean", +        "@id": "pt:waitTranscoding" +      }, +      "support": { +        "@type": "sc:Text", +        "@id": "pt:support" +      }, +      "likes": { +        "@id": "as:likes", +        "@type": "@id" +      }, +      "dislikes": { +        "@id": "as:dislikes", +        "@type": "@id" +      }, +      "playlists": { +        "@id": "pt:playlists", +        "@type": "@id" +      }, +      "shares": { +        "@id": "as:shares", +        "@type": "@id" +      }, +      "comments": { +        "@id": "as:comments", +        "@type": "@id" +      } +    } +  ], +  "summary": null +} diff --git a/test/fixtures/peertube/video-object-mpegURL-only.json b/test/fixtures/peertube/video-object-mpegURL-only.json new file mode 100644 index 000000000..7f26e89bf --- /dev/null +++ b/test/fixtures/peertube/video-object-mpegURL-only.json @@ -0,0 +1,413 @@ +{ +  "type": "Create", +  "id": "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6/activity", +  "actor": "https://peertube.stream/accounts/createurs", +  "object": { +    "type": "Video", +    "id": "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6", +    "name": "Vu du 20/02/21 : \"Planète Mars 2050\"", +    "duration": "PT385S", +    "uuid": "abece3c3-b9c6-47f4-8040-f3eed8c602e6", +    "tag": [ +      { +        "type": "Hashtag", +        "name": "France3" +      }, +      { +        "type": "Hashtag", +        "name": "lezapping" +      } +    ], +    "category": { +      "identifier": "11", +      "name": "News & Politics" +    }, +    "language": { +      "identifier": "fr", +      "name": "French" +    }, +    "views": 5, +    "sensitive": false, +    "waitTranscoding": false, +    "isLiveBroadcast": false, +    "liveSaveReplay": null, +    "permanentLive": null, +    "state": 1, +    "commentsEnabled": true, +    "downloadEnabled": false, +    "published": "2021-02-20T17:04:54.278Z", +    "originallyPublishedAt": "2021-02-19T23:00:00.000Z", +    "updated": "2021-02-21T20:01:11.189Z", +    "mediaType": "text/markdown", +    "content": "Un regard impertinent et libre, orchestré par Patrick Menais et son équipe, sur le monde de l’image.\r\n\r\nEn avant-première du lundi au samedi à 17h00 sur Facebook, Twitter et YouTube.\r\n\r\nDu lundi au samedi à 20h00 sur France 3.\r\n\r\nhttps://www.facebook.com/vufrancetv\r\nhttps://twitter.com/VuFrancetv", +    "support": "Suivre VU :\r\n- Twitter : https://twitter.com/vufrancetv\r\n- Facebook :https://www.facebook.com/vufrancetv/\r\n- Site : https://www.france.tv/france-3/vu/", +    "subtitleLanguage": [], +    "icon": [ +      { +        "type": "Image", +        "url": "https://peertube.stream/static/thumbnails/abece3c3-b9c6-47f4-8040-f3eed8c602e6.jpg", +        "mediaType": "image/jpeg", +        "width": 223, +        "height": 122 +      }, +      { +        "type": "Image", +        "url": "https://peertube.stream/lazy-static/previews/abece3c3-b9c6-47f4-8040-f3eed8c602e6.jpg", +        "mediaType": "image/jpeg", +        "width": 850, +        "height": 480 +      } +    ], +    "url": [ +      { +        "type": "Link", +        "mediaType": "text/html", +        "href": "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6" +      }, +      { +        "type": "Link", +        "mediaType": "application/x-mpegURL", +        "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/master.m3u8", +        "tag": [ +          { +            "type": "Infohash", +            "name": "00bfce9595e1655d8696b60e19ca25c34be5fa63" +          }, +          { +            "type": "Infohash", +            "name": "256c21b65d5e0f944b4b79d8e0cbc55c9d906807" +          }, +          { +            "type": "Infohash", +            "name": "fcd981098c484d0e328927c8fb21ecf986880b7e" +          }, +          { +            "type": "Infohash", +            "name": "f7e01ac566e9fef91cd22514e6c3c256af7a9f5f" +          }, +          { +            "type": "Infohash", +            "name": "42b421fc44d0dceb45ac3f6f6419b07fd570a232" +          }, +          { +            "type": "Infohash", +            "name": "f876c6d6d49ce618a880ca223df54cb29f4b4bfd" +          }, +          { +            "type": "Link", +            "name": "sha256", +            "mediaType": "application/json", +            "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/segments-sha256.json" +          }, +          { +            "type": "Link", +            "mediaType": "video/mp4", +            "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/abece3c3-b9c6-47f4-8040-f3eed8c602e6-1080-fragmented.mp4", +            "height": 1080, +            "size": 57888169, +            "fps": 25 +          }, +          { +            "type": "Link", +            "rel": [ +              "metadata", +              "video/mp4" +            ], +            "mediaType": "application/json", +            "href": "https://peertube.stream/api/v1/videos/abece3c3-b9c6-47f4-8040-f3eed8c602e6/metadata/570040", +            "height": 1080, +            "fps": 25 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent", +            "href": "https://peertube.stream/static/torrents/abece3c3-b9c6-47f4-8040-f3eed8c602e6-1080-hls.torrent", +            "height": 1080 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent;x-scheme-handler/magnet", +            "href": "magnet:?xs=https%3A%2F%2Fpeertube.stream%2Fstatic%2Ftorrents%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-1080-hls.torrent&xt=urn:btih:68af82ebcd9df8335e407b755f38f5fd39c8a6a4&dn=Vu+du+20%2F02%2F21+%3A+%22Plan%C3%A8te+Mars+2050%22&tr=wss%3A%2F%2Fpeertube.stream%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.stream%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.stream%2Fstatic%2Fstreaming-playlists%2Fhls%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-1080-fragmented.mp4", +            "height": 1080 +          }, +          { +            "type": "Link", +            "mediaType": "video/mp4", +            "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/abece3c3-b9c6-47f4-8040-f3eed8c602e6-720-fragmented.mp4", +            "height": 720, +            "size": 45165123, +            "fps": 25 +          }, +          { +            "type": "Link", +            "rel": [ +              "metadata", +              "video/mp4" +            ], +            "mediaType": "application/json", +            "href": "https://peertube.stream/api/v1/videos/abece3c3-b9c6-47f4-8040-f3eed8c602e6/metadata/570056", +            "height": 720, +            "fps": 25 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent", +            "href": "https://peertube.stream/static/torrents/abece3c3-b9c6-47f4-8040-f3eed8c602e6-720-hls.torrent", +            "height": 720 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent;x-scheme-handler/magnet", +            "href": "magnet:?xs=https%3A%2F%2Fpeertube.stream%2Fstatic%2Ftorrents%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-720-hls.torrent&xt=urn:btih:8450928a4ffb2a4c5f927a163487c48c05f6e700&dn=Vu+du+20%2F02%2F21+%3A+%22Plan%C3%A8te+Mars+2050%22&tr=wss%3A%2F%2Fpeertube.stream%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.stream%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.stream%2Fstatic%2Fstreaming-playlists%2Fhls%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-720-fragmented.mp4", +            "height": 720 +          }, +          { +            "type": "Link", +            "mediaType": "video/mp4", +            "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/abece3c3-b9c6-47f4-8040-f3eed8c602e6-480-fragmented.mp4", +            "height": 480, +            "size": 29618534, +            "fps": 25 +          }, +          { +            "type": "Link", +            "rel": [ +              "metadata", +              "video/mp4" +            ], +            "mediaType": "application/json", +            "href": "https://peertube.stream/api/v1/videos/abece3c3-b9c6-47f4-8040-f3eed8c602e6/metadata/570042", +            "height": 480, +            "fps": 25 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent", +            "href": "https://peertube.stream/static/torrents/abece3c3-b9c6-47f4-8040-f3eed8c602e6-480-hls.torrent", +            "height": 480 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent;x-scheme-handler/magnet", +            "href": "magnet:?xs=https%3A%2F%2Fpeertube.stream%2Fstatic%2Ftorrents%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-480-hls.torrent&xt=urn:btih:39e11181db5f376aa78c94bffcb9ccf2f4bca715&dn=Vu+du+20%2F02%2F21+%3A+%22Plan%C3%A8te+Mars+2050%22&tr=wss%3A%2F%2Fpeertube.stream%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.stream%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.stream%2Fstatic%2Fstreaming-playlists%2Fhls%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-480-fragmented.mp4", +            "height": 480 +          }, +          { +            "type": "Link", +            "mediaType": "video/mp4", +            "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/abece3c3-b9c6-47f4-8040-f3eed8c602e6-360-fragmented.mp4", +            "height": 360, +            "size": 21771466, +            "fps": 25 +          }, +          { +            "type": "Link", +            "rel": [ +              "metadata", +              "video/mp4" +            ], +            "mediaType": "application/json", +            "href": "https://peertube.stream/api/v1/videos/abece3c3-b9c6-47f4-8040-f3eed8c602e6/metadata/570043", +            "height": 360, +            "fps": 25 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent", +            "href": "https://peertube.stream/static/torrents/abece3c3-b9c6-47f4-8040-f3eed8c602e6-360-hls.torrent", +            "height": 360 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent;x-scheme-handler/magnet", +            "href": "magnet:?xs=https%3A%2F%2Fpeertube.stream%2Fstatic%2Ftorrents%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-360-hls.torrent&xt=urn:btih:c33aa52822528e29ffd1a615ebe40450e4c61452&dn=Vu+du+20%2F02%2F21+%3A+%22Plan%C3%A8te+Mars+2050%22&tr=wss%3A%2F%2Fpeertube.stream%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.stream%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.stream%2Fstatic%2Fstreaming-playlists%2Fhls%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-360-fragmented.mp4", +            "height": 360 +          }, +          { +            "type": "Link", +            "mediaType": "video/mp4", +            "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/abece3c3-b9c6-47f4-8040-f3eed8c602e6-240-fragmented.mp4", +            "height": 240, +            "size": 14856165, +            "fps": 25 +          }, +          { +            "type": "Link", +            "rel": [ +              "metadata", +              "video/mp4" +            ], +            "mediaType": "application/json", +            "href": "https://peertube.stream/api/v1/videos/abece3c3-b9c6-47f4-8040-f3eed8c602e6/metadata/570057", +            "height": 240, +            "fps": 25 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent", +            "href": "https://peertube.stream/static/torrents/abece3c3-b9c6-47f4-8040-f3eed8c602e6-240-hls.torrent", +            "height": 240 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent;x-scheme-handler/magnet", +            "href": "magnet:?xs=https%3A%2F%2Fpeertube.stream%2Fstatic%2Ftorrents%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-240-hls.torrent&xt=urn:btih:157e4cc3e9f15c06e995d6c3388539fdda312771&dn=Vu+du+20%2F02%2F21+%3A+%22Plan%C3%A8te+Mars+2050%22&tr=wss%3A%2F%2Fpeertube.stream%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.stream%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.stream%2Fstatic%2Fstreaming-playlists%2Fhls%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-240-fragmented.mp4", +            "height": 240 +          }, +          { +            "type": "Link", +            "mediaType": "video/mp4", +            "href": "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/abece3c3-b9c6-47f4-8040-f3eed8c602e6-0-fragmented.mp4", +            "height": 0, +            "size": 6248765, +            "fps": 0 +          }, +          { +            "type": "Link", +            "rel": [ +              "metadata", +              "video/mp4" +            ], +            "mediaType": "application/json", +            "href": "https://peertube.stream/api/v1/videos/abece3c3-b9c6-47f4-8040-f3eed8c602e6/metadata/570041", +            "height": 0, +            "fps": 0 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent", +            "href": "https://peertube.stream/static/torrents/abece3c3-b9c6-47f4-8040-f3eed8c602e6-0-hls.torrent", +            "height": 0 +          }, +          { +            "type": "Link", +            "mediaType": "application/x-bittorrent;x-scheme-handler/magnet", +            "href": "magnet:?xs=https%3A%2F%2Fpeertube.stream%2Fstatic%2Ftorrents%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-0-hls.torrent&xt=urn:btih:abc8dc58903d18cf7ec0c0cef92cc5ffe5cb0b5c&dn=Vu+du+20%2F02%2F21+%3A+%22Plan%C3%A8te+Mars+2050%22&tr=wss%3A%2F%2Fpeertube.stream%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube.stream%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube.stream%2Fstatic%2Fstreaming-playlists%2Fhls%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6%2Fabece3c3-b9c6-47f4-8040-f3eed8c602e6-0-fragmented.mp4", +            "height": 0 +          } +        ] +      } +    ], +    "likes": "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6/likes", +    "dislikes": "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6/dislikes", +    "shares": "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6/announces", +    "comments": "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6/comments", +    "attributedTo": [ +      { +        "type": "Person", +        "id": "https://peertube.stream/accounts/createurs" +      }, +      { +        "type": "Group", +        "id": "https://peertube.stream/video-channels/vu" +      } +    ], +    "to": [ +      "https://www.w3.org/ns/activitystreams#Public" +    ], +    "cc": [ +      "https://peertube.stream/accounts/createurs/followers" +    ] +  }, +  "to": [ +    "https://www.w3.org/ns/activitystreams#Public" +  ], +  "cc": [ +    "https://peertube.stream/accounts/createurs/followers" +  ], +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    "https://w3id.org/security/v1", +    { +      "RsaSignature2017": "https://w3id.org/security#RsaSignature2017" +    }, +    { +      "pt": "https://joinpeertube.org/ns#", +      "sc": "http://schema.org#", +      "Hashtag": "as:Hashtag", +      "uuid": "sc:identifier", +      "category": "sc:category", +      "licence": "sc:license", +      "subtitleLanguage": "sc:subtitleLanguage", +      "sensitive": "as:sensitive", +      "language": "sc:inLanguage", +      "isLiveBroadcast": "sc:isLiveBroadcast", +      "liveSaveReplay": { +        "@type": "sc:Boolean", +        "@id": "pt:liveSaveReplay" +      }, +      "permanentLive": { +        "@type": "sc:Boolean", +        "@id": "pt:permanentLive" +      }, +      "Infohash": "pt:Infohash", +      "Playlist": "pt:Playlist", +      "PlaylistElement": "pt:PlaylistElement", +      "originallyPublishedAt": "sc:datePublished", +      "views": { +        "@type": "sc:Number", +        "@id": "pt:views" +      }, +      "state": { +        "@type": "sc:Number", +        "@id": "pt:state" +      }, +      "size": { +        "@type": "sc:Number", +        "@id": "pt:size" +      }, +      "fps": { +        "@type": "sc:Number", +        "@id": "pt:fps" +      }, +      "startTimestamp": { +        "@type": "sc:Number", +        "@id": "pt:startTimestamp" +      }, +      "stopTimestamp": { +        "@type": "sc:Number", +        "@id": "pt:stopTimestamp" +      }, +      "position": { +        "@type": "sc:Number", +        "@id": "pt:position" +      }, +      "commentsEnabled": { +        "@type": "sc:Boolean", +        "@id": "pt:commentsEnabled" +      }, +      "downloadEnabled": { +        "@type": "sc:Boolean", +        "@id": "pt:downloadEnabled" +      }, +      "waitTranscoding": { +        "@type": "sc:Boolean", +        "@id": "pt:waitTranscoding" +      }, +      "support": { +        "@type": "sc:Text", +        "@id": "pt:support" +      }, +      "likes": { +        "@id": "as:likes", +        "@type": "@id" +      }, +      "dislikes": { +        "@id": "as:dislikes", +        "@type": "@id" +      }, +      "playlists": { +        "@id": "pt:playlists", +        "@type": "@id" +      }, +      "shares": { +        "@id": "as:shares", +        "@type": "@id" +      }, +      "comments": { +        "@id": "as:comments", +        "@type": "@id" +      } +    } +  ] +} diff --git a/test/fixtures/statuses/masto-note.json b/test/fixtures/statuses/masto-note.json new file mode 100644 index 000000000..6b96de473 --- /dev/null +++ b/test/fixtures/statuses/masto-note.json @@ -0,0 +1,47 @@ +{ +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    { +      "ostatus": "http://ostatus.org#", +      "atomUri": "ostatus:atomUri", +      "inReplyToAtomUri": "ostatus:inReplyToAtomUri", +      "conversation": "ostatus:conversation", +      "sensitive": "as:sensitive", +      "toot": "http://joinmastodon.org/ns#", +      "votersCount": "toot:votersCount" +    } +  ], +  "id": "https://example.com/users/{{nickname}}/statuses/{{status_id}}", +  "type": "Note", +  "summary": null, +  "inReplyTo": null, +  "published": "2021-02-24T12:40:49Z", +  "url": "https://example.com/@{{nickname}}/{{status_id}}", +  "attributedTo": "https://example.com/users/{{nickname}}", +  "to": [ +    "https://www.w3.org/ns/activitystreams#Public" +  ], +  "cc": [ +    "https://example.com/users/{{nickname}}/followers" +  ], +  "sensitive": false, +  "atomUri": "https://example.com/users/{{nickname}}/statuses/{{status_id}}", +  "inReplyToAtomUri": null, +  "conversation": "tag:example.com,2021-02-24:objectId=15:objectType=Conversation", +  "content": "<p></p>", +  "contentMap": { +    "en": "<p></p>" +  }, +  "attachment": [], +  "tag": [], +  "replies": { +    "id": "https://example.com/users/{{nickname}}/statuses/{{status_id}}/replies", +    "type": "Collection", +    "first": { +      "type": "CollectionPage", +      "next": "https://example.com/users/{{nickname}}/statuses/{{status_id}}/replies?only_other_accounts=true&page=true", +      "partOf": "https://example.com/users/{{nickname}}/statuses/{{status_id}}/replies", +      "items": [] +    } +  } +} diff --git a/test/fixtures/statuses/note.json b/test/fixtures/statuses/note.json new file mode 100644 index 000000000..41735cbc5 --- /dev/null +++ b/test/fixtures/statuses/note.json @@ -0,0 +1,27 @@ +{ +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    "https://example.com/schemas/litepub-0.1.jsonld", +    { +      "@language": "und" +    } +  ], +  "actor": "https://example.com/users/{{nickname}}", +  "attachment": [], +  "attributedTo": "https://example.com/users/{{nickname}}", +  "cc": [ +    "https://example.com/users/{{nickname}}/followers" +  ], +  "content": "Content", +  "context": "https://example.com/contexts/e4b180e1-7403-477f-aeb4-de57e7a3fe7f", +  "conversation": "https://example.com/contexts/e4b180e1-7403-477f-aeb4-de57e7a3fe7f", +  "id": "https://example.com/objects/{{object_id}}", +  "published": "2019-12-15T22:00:05.279583Z", +  "sensitive": false, +  "summary": "", +  "tag": [], +  "to": [ +    "https://www.w3.org/ns/activitystreams#Public" +  ], +  "type": "Note" +} diff --git a/test/fixtures/tesla_mock/emoji-in-summary.json b/test/fixtures/tesla_mock/emoji-in-summary.json new file mode 100644 index 000000000..f77c6e2e8 --- /dev/null +++ b/test/fixtures/tesla_mock/emoji-in-summary.json @@ -0,0 +1,49 @@ +{ +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    "https://patch.cx/schemas/litepub-0.1.jsonld", +    { +      "@language": "und" +    } +  ], +  "actor": "https://patch.cx/users/rin", +  "attachment": [], +  "attributedTo": "https://patch.cx/users/rin", +  "cc": [ +    "https://patch.cx/users/rin/followers" +  ], +  "content": ":joker_disapprove: <br><br>just grabbing a test fixture, nevermind me", +  "context": "https://patch.cx/contexts/2c3ce4b4-18b1-4b1a-8965-3932027b5326", +  "conversation": "https://patch.cx/contexts/2c3ce4b4-18b1-4b1a-8965-3932027b5326", +  "id": "https://patch.cx/objects/a399c28e-c821-4820-bc3e-4afeb044c16f", +  "published": "2021-03-22T16:54:46.461939Z", +  "sensitive": null, +  "source": ":joker_disapprove: \r\n\r\njust grabbing a test fixture, nevermind me", +  "summary": ":joker_smile: ", +  "tag": [ +    { +      "icon": { +        "type": "Image", +        "url": "https://patch.cx/emoji/custom/joker_disapprove.png" +      }, +      "id": "https://patch.cx/emoji/custom/joker_disapprove.png", +      "name": ":joker_disapprove:", +      "type": "Emoji", +      "updated": "1970-01-01T00:00:00Z" +    }, +    { +      "icon": { +        "type": "Image", +        "url": "https://patch.cx/emoji/custom/joker_smile.png" +      }, +      "id": "https://patch.cx/emoji/custom/joker_smile.png", +      "name": ":joker_smile:", +      "type": "Emoji", +      "updated": "1970-01-01T00:00:00Z" +    } +  ], +  "to": [ +    "https://www.w3.org/ns/activitystreams#Public" +  ], +  "type": "Note" +} diff --git a/test/fixtures/tesla_mock/xn--q9jyb4c_host_meta b/test/fixtures/tesla_mock/xn--q9jyb4c_host_meta deleted file mode 100644 index 45d260e55..000000000 --- a/test/fixtures/tesla_mock/xn--q9jyb4c_host_meta +++ /dev/null @@ -1,4 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"> -    <Link rel="lrdd" template="https://zetsubou.xn--q9jyb4c/.well-known/webfinger?resource={uri}" type="application/xrd+xml" /> -</XRD> diff --git a/test/fixtures/users_mock/localhost.json b/test/fixtures/users_mock/localhost.json deleted file mode 100644 index a49935db1..000000000 --- a/test/fixtures/users_mock/localhost.json +++ /dev/null @@ -1,41 +0,0 @@ -{ -  "@context": [ -    "https://www.w3.org/ns/activitystreams", -    "http://localhost:4001/schemas/litepub-0.1.jsonld", -    { -      "@language": "und" -    } -  ], -  "attachment": [], -  "endpoints": { -    "oauthAuthorizationEndpoint": "http://localhost:4001/oauth/authorize", -    "oauthRegistrationEndpoint": "http://localhost:4001/api/v1/apps", -    "oauthTokenEndpoint": "http://localhost:4001/oauth/token", -    "sharedInbox": "http://localhost:4001/inbox" -  }, -  "followers": "http://localhost:4001/users/{{nickname}}/followers", -  "following": "http://localhost:4001/users/{{nickname}}/following", -  "icon": { -    "type": "Image", -    "url": "http://localhost:4001/media/4e914f5b84e4a259a3f6c2d2edc9ab642f2ab05f3e3d9c52c81fc2d984b3d51e.jpg" -  }, -  "id": "http://localhost:4001/users/{{nickname}}", -  "image": { -    "type": "Image", -    "url": "http://localhost:4001/media/f739efddefeee49c6e67e947c4811fdc911785c16ae43da4c3684051fbf8da6a.jpg?name=f739efddefeee49c6e67e947c4811fdc911785c16ae43da4c3684051fbf8da6a.jpg" -  }, -  "inbox": "http://localhost:4001/users/{{nickname}}/inbox", -  "manuallyApprovesFollowers": false, -  "name": "{{nickname}}", -  "outbox": "http://localhost:4001/users/{{nickname}}/outbox", -  "preferredUsername": "{{nickname}}", -  "publicKey": { -    "id": "http://localhost:4001/users/{{nickname}}#main-key", -    "owner": "http://localhost:4001/users/{{nickname}}", -    "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5DLtwGXNZElJyxFGfcVc\nXANhaMadj/iYYQwZjOJTV9QsbtiNBeIK54PJrYuU0/0YIdrvS1iqheX5IwXRhcwa\nhm3ZyLz7XeN9st7FBni4BmZMBtMpxAuYuu5p/jbWy13qAiYOhPreCx0wrWgm/lBD\n9mkgaxIxPooBE0S4ZWEJIDIV1Vft3AWcRUyWW1vIBK0uZzs6GYshbQZB952S0yo4\nFzI1hABGHncH8UvuFauh4EZ8tY7/X5I0pGRnDOcRN1dAht5w5yTA+6r5kebiFQjP\nIzN/eCO/a9Flrj9YGW7HDNtjSOH0A31PLRGlJtJO3yK57dnf5ppyCZGfL4emShQo\ncQIDAQAB\n-----END PUBLIC KEY-----\n\n" -  }, -  "summary": "your friendly neighborhood pleroma developer<br>I like cute things and distributed systems, and really hate delete and redrafts", -  "tag": [], -  "type": "Person", -  "url": "http://localhost:4001/users/{{nickname}}" -}
\ No newline at end of file diff --git a/test/fixtures/users_mock/masto_featured.json b/test/fixtures/users_mock/masto_featured.json new file mode 100644 index 000000000..646a343ad --- /dev/null +++ b/test/fixtures/users_mock/masto_featured.json @@ -0,0 +1,18 @@ +{ +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    { +      "ostatus": "http://ostatus.org#", +      "atomUri": "ostatus:atomUri", +      "inReplyToAtomUri": "ostatus:inReplyToAtomUri", +      "conversation": "ostatus:conversation", +      "sensitive": "as:sensitive", +      "toot": "http://joinmastodon.org/ns#", +      "votersCount": "toot:votersCount" +    } +  ], +  "id": "https://{{domain}}/users/{{nickname}}/collections/featured", +  "type": "OrderedCollection", +  "totalItems": 0, +  "orderedItems": [] +} diff --git a/test/fixtures/users_mock/user.json b/test/fixtures/users_mock/user.json new file mode 100644 index 000000000..c722a1145 --- /dev/null +++ b/test/fixtures/users_mock/user.json @@ -0,0 +1,42 @@ +{ +  "@context": [ +    "https://www.w3.org/ns/activitystreams", +    "https://example.com/schemas/litepub-0.1.jsonld", +    { +      "@language": "und" +    } +  ], +  "attachment": [], +  "endpoints": { +    "oauthAuthorizationEndpoint": "https://example.com/oauth/authorize", +    "oauthRegistrationEndpoint": "https://example.com/api/v1/apps", +    "oauthTokenEndpoint": "https://example.com/oauth/token", +    "sharedInbox": "https://example.com/inbox" +  }, +  "followers": "https://example.com/users/{{nickname}}/followers", +  "following": "https://example.com/users/{{nickname}}/following", +  "icon": { +    "type": "Image", +    "url": "https://example.com/media/4e914f5b84e4a259a3f6c2d2edc9ab642f2ab05f3e3d9c52c81fc2d984b3d51e.jpg" +  }, +  "id": "https://example.com/users/{{nickname}}", +  "image": { +    "type": "Image", +    "url": "https://example.com/media/f739efddefeee49c6e67e947c4811fdc911785c16ae43da4c3684051fbf8da6a.jpg?name=f739efddefeee49c6e67e947c4811fdc911785c16ae43da4c3684051fbf8da6a.jpg" +  }, +  "inbox": "https://example.com/users/{{nickname}}/inbox", +  "manuallyApprovesFollowers": false, +  "name": "{{nickname}}", +  "outbox": "https://example.com/users/{{nickname}}/outbox", +  "preferredUsername": "{{nickname}}", +  "publicKey": { +    "id": "https://example.com/users/{{nickname}}#main-key", +    "owner": "https://example.com/users/{{nickname}}", +    "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5DLtwGXNZElJyxFGfcVc\nXANhaMadj/iYYQwZjOJTV9QsbtiNBeIK54PJrYuU0/0YIdrvS1iqheX5IwXRhcwa\nhm3ZyLz7XeN9st7FBni4BmZMBtMpxAuYuu5p/jbWy13qAiYOhPreCx0wrWgm/lBD\n9mkgaxIxPooBE0S4ZWEJIDIV1Vft3AWcRUyWW1vIBK0uZzs6GYshbQZB952S0yo4\nFzI1hABGHncH8UvuFauh4EZ8tY7/X5I0pGRnDOcRN1dAht5w5yTA+6r5kebiFQjP\nIzN/eCO/a9Flrj9YGW7HDNtjSOH0A31PLRGlJtJO3yK57dnf5ppyCZGfL4emShQo\ncQIDAQAB\n-----END PUBLIC KEY-----\n\n" +  }, +  "featured": "https://example.com/users/{{nickname}}/collections/featured", +  "summary": "your friendly neighborhood pleroma developer<br>I like cute things and distributed systems, and really hate delete and redrafts", +  "tag": [], +  "type": "Person", +  "url": "https://example.com/users/{{nickname}}" +} diff --git a/test/mix/pleroma_test.exs b/test/mix/pleroma_test.exs index c3e47b285..af62cc1d9 100644 --- a/test/mix/pleroma_test.exs +++ b/test/mix/pleroma_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.PleromaTest do diff --git a/test/mix/tasks/pleroma/app_test.exs b/test/mix/tasks/pleroma/app_test.exs index 71a84ac8e..9eabd32af 100644 --- a/test/mix/tasks/pleroma/app_test.exs +++ b/test/mix/tasks/pleroma/app_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.AppTest do diff --git a/test/mix/tasks/pleroma/config_test.exs b/test/mix/tasks/pleroma/config_test.exs index 0280d208d..3ed1e94b8 100644 --- a/test/mix/tasks/pleroma/config_test.exs +++ b/test/mix/tasks/pleroma/config_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.ConfigTest do @@ -200,6 +200,44 @@ defmodule Mix.Tasks.Pleroma.ConfigTest do      end    end +  describe "migrate_from_db/1" do +    setup do: clear_config(:configurable_from_database, true) + +    setup do +      insert_config_record(:pleroma, :setting_first, key: "value", key2: ["Activity"]) +      insert_config_record(:pleroma, :setting_second, key: "value2", key2: [Repo]) +      insert_config_record(:quack, :level, :info) + +      path = "test/instance_static" +      file_path = Path.join(path, "temp.exported_from_db.secret.exs") + +      on_exit(fn -> File.rm!(file_path) end) + +      [file_path: file_path] +    end + +    test "with path parameter", %{file_path: file_path} do +      MixTask.run(["migrate_from_db", "--env", "temp", "--path", Path.dirname(file_path)]) + +      file = File.read!(file_path) +      assert file =~ "config :pleroma, :setting_first," +      assert file =~ "config :pleroma, :setting_second," +      assert file =~ "config :quack, :level, :info" +    end + +    test "release", %{file_path: file_path} do +      clear_config(:release, true) +      clear_config(:config_path, file_path) + +      MixTask.run(["migrate_from_db", "--env", "temp"]) + +      file = File.read!(file_path) +      assert file =~ "config :pleroma, :setting_first," +      assert file =~ "config :pleroma, :setting_second," +      assert file =~ "config :quack, :level, :info" +    end +  end +    describe "operations on database config" do      setup do: clear_config(:configurable_from_database, true) diff --git a/test/mix/tasks/pleroma/count_statuses_test.exs b/test/mix/tasks/pleroma/count_statuses_test.exs index c5cd16960..80ec206b8 100644 --- a/test/mix/tasks/pleroma/count_statuses_test.exs +++ b/test/mix/tasks/pleroma/count_statuses_test.exs @@ -1,8 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.CountStatusesTest do +  # Uses log capture, has to stay synchronous    use Pleroma.DataCase    alias Pleroma.User diff --git a/test/mix/tasks/pleroma/database_test.exs b/test/mix/tasks/pleroma/database_test.exs index a4bd41922..7a1a759da 100644 --- a/test/mix/tasks/pleroma/database_test.exs +++ b/test/mix/tasks/pleroma/database_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.DatabaseTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    use Oban.Testing, repo: Pleroma.Repo    alias Pleroma.Activity @@ -87,7 +87,8 @@ defmodule Mix.Tasks.Pleroma.DatabaseTest do        assert user.follower_count == 3 -      assert :ok == Mix.Tasks.Pleroma.Database.run(["update_users_following_followers_counts"]) +      assert {:ok, :ok} == +               Mix.Tasks.Pleroma.Database.run(["update_users_following_followers_counts"])        user = User.get_by_id(user.id) diff --git a/test/mix/tasks/pleroma/digest_test.exs b/test/mix/tasks/pleroma/digest_test.exs index 69dccb745..4a9e461a9 100644 --- a/test/mix/tasks/pleroma/digest_test.exs +++ b/test/mix/tasks/pleroma/digest_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.DigestTest do diff --git a/test/mix/tasks/pleroma/ecto/migrate_test.exs b/test/mix/tasks/pleroma/ecto/migrate_test.exs index 43df176a1..5bdfd8f30 100644 --- a/test/mix/tasks/pleroma/ecto/migrate_test.exs +++ b/test/mix/tasks/pleroma/ecto/migrate_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-onl  defmodule Mix.Tasks.Pleroma.Ecto.MigrateTest do -  use Pleroma.DataCase, async: true +  use Pleroma.DataCase    import ExUnit.CaptureLog    require Logger diff --git a/test/mix/tasks/pleroma/ecto/rollback_test.exs b/test/mix/tasks/pleroma/ecto/rollback_test.exs index 0236e35d5..f8a37bd49 100644 --- a/test/mix/tasks/pleroma/ecto/rollback_test.exs +++ b/test/mix/tasks/pleroma/ecto/rollback_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.Ecto.RollbackTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import ExUnit.CaptureLog    require Logger @@ -12,7 +12,7 @@ defmodule Mix.Tasks.Pleroma.Ecto.RollbackTest do      Logger.configure(level: :warn)      assert capture_log(fn -> -             Mix.Tasks.Pleroma.Ecto.Rollback.run() +             Mix.Tasks.Pleroma.Ecto.Rollback.run(["--env", "test"])             end) =~ "[info] Rollback succesfully"      Logger.configure(level: level) diff --git a/test/mix/tasks/pleroma/ecto_test.exs b/test/mix/tasks/pleroma/ecto_test.exs index 3a028df83..0164da5a8 100644 --- a/test/mix/tasks/pleroma/ecto_test.exs +++ b/test/mix/tasks/pleroma/ecto_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.EctoTest do diff --git a/test/mix/tasks/pleroma/email_test.exs b/test/mix/tasks/pleroma/email_test.exs index 9523aefd8..ce68b88de 100644 --- a/test/mix/tasks/pleroma/email_test.exs +++ b/test/mix/tasks/pleroma/email_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.EmailTest do @@ -61,18 +61,18 @@ defmodule Mix.Tasks.Pleroma.EmailTest do      test "Sends confirmation emails" do        local_user1 =          insert(:user, %{ -          confirmation_pending: true, +          is_confirmed: false,            confirmation_token: "mytoken", -          deactivated: false, +          is_active: true,            email: "local1@pleroma.com",            local: true          })        local_user2 =          insert(:user, %{ -          confirmation_pending: true, +          is_confirmed: false,            confirmation_token: "mytoken", -          deactivated: false, +          is_active: true,            email: "local2@pleroma.com",            local: true          }) @@ -88,30 +88,30 @@ defmodule Mix.Tasks.Pleroma.EmailTest do      test "Does not send confirmation email to inappropriate users" do        # confirmed user        insert(:user, %{ -        confirmation_pending: false, +        is_confirmed: true,          confirmation_token: "mytoken", -        deactivated: false, +        is_active: true,          email: "confirmed@pleroma.com",          local: true        })        # remote user        insert(:user, %{ -        deactivated: false, +        is_active: true,          email: "remote@not-pleroma.com",          local: false        })        # deactivated user =        insert(:user, %{ -        deactivated: true, +        is_active: false,          email: "deactivated@pleroma.com",          local: false        })        # invisible user        insert(:user, %{ -        deactivated: false, +        is_active: true,          email: "invisible@pleroma.com",          local: true,          invisible: true diff --git a/test/mix/tasks/pleroma/emoji_test.exs b/test/mix/tasks/pleroma/emoji_test.exs index 0fb8603ac..bd20f285c 100644 --- a/test/mix/tasks/pleroma/emoji_test.exs +++ b/test/mix/tasks/pleroma/emoji_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.EmojiTest do diff --git a/test/mix/tasks/pleroma/frontend_test.exs b/test/mix/tasks/pleroma/frontend_test.exs index 6f9ec14cd..aa4b25ebb 100644 --- a/test/mix/tasks/pleroma/frontend_test.exs +++ b/test/mix/tasks/pleroma/frontend_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.FrontendTest do diff --git a/test/mix/tasks/pleroma/instance_test.exs b/test/mix/tasks/pleroma/instance_test.exs index 6580fc932..5a5a68053 100644 --- a/test/mix/tasks/pleroma/instance_test.exs +++ b/test/mix/tasks/pleroma/instance_test.exs @@ -1,9 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.InstanceTest do -  use ExUnit.Case +  # Modifies the Application Environment, has to stay synchronous. +  use Pleroma.DataCase    setup do      File.mkdir_p!(tmp_path()) @@ -15,15 +16,17 @@ defmodule Mix.Tasks.Pleroma.InstanceTest do        if File.exists?(static_dir) do          File.rm_rf(Path.join(static_dir, "robots.txt"))        end - -      Pleroma.Config.put([:instance, :static_dir], static_dir)      end) +    # Is being modified by the mix task. +    clear_config([:instance, :static_dir]) +      :ok    end +  @uuid Ecto.UUID.generate()    defp tmp_path do -    "/tmp/generated_files/" +    "/tmp/generated_files/#{@uuid}/"    end    test "running gen" do diff --git a/test/mix/tasks/pleroma/refresh_counter_cache_test.exs b/test/mix/tasks/pleroma/refresh_counter_cache_test.exs index 6a1a9ac17..fe9e5cfeb 100644 --- a/test/mix/tasks/pleroma/refresh_counter_cache_test.exs +++ b/test/mix/tasks/pleroma/refresh_counter_cache_test.exs @@ -1,8 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.RefreshCounterCacheTest do +  # Uses log capture, has to stay synchronous    use Pleroma.DataCase    alias Pleroma.Web.CommonAPI    import ExUnit.CaptureIO, only: [capture_io: 1] diff --git a/test/mix/tasks/pleroma/relay_test.exs b/test/mix/tasks/pleroma/relay_test.exs index cf48e7dda..db75b3630 100644 --- a/test/mix/tasks/pleroma/relay_test.exs +++ b/test/mix/tasks/pleroma/relay_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.RelayTest do @@ -100,7 +100,7 @@ defmodule Mix.Tasks.Pleroma.RelayTest do        end)        Pleroma.Repo.delete(user) -      Cachex.clear(:user_cache) +      User.invalidate_cache(user)        Mix.Tasks.Pleroma.Relay.run(["unfollow", target_instance]) @@ -137,7 +137,7 @@ defmodule Mix.Tasks.Pleroma.RelayTest do        end)        Pleroma.Repo.delete(user) -      Cachex.clear(:user_cache) +      User.invalidate_cache(user)        Mix.Tasks.Pleroma.Relay.run(["unfollow", target_instance, "--force"]) diff --git a/test/mix/tasks/pleroma/robots_txt_test.exs b/test/mix/tasks/pleroma/robots_txt_test.exs index 7040a0e4e..028aa4ccc 100644 --- a/test/mix/tasks/pleroma/robots_txt_test.exs +++ b/test/mix/tasks/pleroma/robots_txt_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.RobotsTxtTest do @@ -12,7 +12,7 @@ defmodule Mix.Tasks.Pleroma.RobotsTxtTest do    test "creates new dir" do      path = "test/fixtures/new_dir/"      file_path = path <> "robots.txt" -    Pleroma.Config.put([:instance, :static_dir], path) +    clear_config([:instance, :static_dir], path)      on_exit(fn ->        {:ok, ["test/fixtures/new_dir/", "test/fixtures/new_dir/robots.txt"]} = File.rm_rf(path) @@ -29,7 +29,7 @@ defmodule Mix.Tasks.Pleroma.RobotsTxtTest do    test "to existance folder" do      path = "test/fixtures/"      file_path = path <> "robots.txt" -    Pleroma.Config.put([:instance, :static_dir], path) +    clear_config([:instance, :static_dir], path)      on_exit(fn ->        :ok = File.rm(file_path) diff --git a/test/mix/tasks/pleroma/uploads_test.exs b/test/mix/tasks/pleroma/uploads_test.exs index d69e149a8..a7d15e0fa 100644 --- a/test/mix/tasks/pleroma/uploads_test.exs +++ b/test/mix/tasks/pleroma/uploads_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.UploadsTest do diff --git a/test/mix/tasks/pleroma/user_test.exs b/test/mix/tasks/pleroma/user_test.exs index 127771212..a2178bbd1 100644 --- a/test/mix/tasks/pleroma/user_test.exs +++ b/test/mix/tasks/pleroma/user_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Mix.Tasks.Pleroma.UserTest do @@ -102,7 +102,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do          assert_received {:mix_shell, :info, [message]}          assert message =~ " deleted" -        assert %{deactivated: true} = User.get_by_nickname(user.nickname) +        assert %{is_active: false} = User.get_by_nickname(user.nickname)          assert called(Pleroma.Web.Federator.publish(:_))        end @@ -114,7 +114,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do        {:ok, post} = CommonAPI.post(user, %{status: "uguu"})        {:ok, post2} = CommonAPI.post(user2, %{status: "test"}) -      obj = Object.normalize(post2) +      obj = Object.normalize(post2, fetch: false)        {:ok, like_object, meta} = Pleroma.Web.ActivityPub.Builder.like(user, obj) @@ -130,7 +130,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do        clear_config([:instance, :federating], true) -      object = Object.normalize(post) +      object = Object.normalize(post, fetch: false)        Object.prune(object)        with_mock Pleroma.Web.Federator, @@ -140,7 +140,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do          assert_received {:mix_shell, :info, [message]}          assert message =~ " deleted" -        assert %{deactivated: true} = User.get_by_nickname(user.nickname) +        assert %{is_active: false} = User.get_by_nickname(user.nickname)          assert called(Pleroma.Web.Federator.publish(:_))          refute Pleroma.Repo.get(Pleroma.Activity, like_activity.id) @@ -157,41 +157,8 @@ defmodule Mix.Tasks.Pleroma.UserTest do      end    end -  describe "running toggle_activated" do -    test "user is deactivated" do -      user = insert(:user) - -      Mix.Tasks.Pleroma.User.run(["toggle_activated", user.nickname]) - -      assert_received {:mix_shell, :info, [message]} -      assert message =~ " deactivated" - -      user = User.get_cached_by_nickname(user.nickname) -      assert user.deactivated -    end - -    test "user is activated" do -      user = insert(:user, deactivated: true) - -      Mix.Tasks.Pleroma.User.run(["toggle_activated", user.nickname]) - -      assert_received {:mix_shell, :info, [message]} -      assert message =~ " activated" - -      user = User.get_cached_by_nickname(user.nickname) -      refute user.deactivated -    end - -    test "no user to toggle" do -      Mix.Tasks.Pleroma.User.run(["toggle_activated", "nonexistent"]) - -      assert_received {:mix_shell, :error, [message]} -      assert message =~ "No user" -    end -  end -    describe "running deactivate" do -    test "user is unsubscribed" do +    test "active user is deactivated and unsubscribed" do        followed = insert(:user)        remote_followed = insert(:user, local: false)        user = insert(:user) @@ -201,16 +168,26 @@ defmodule Mix.Tasks.Pleroma.UserTest do        Mix.Tasks.Pleroma.User.run(["deactivate", user.nickname]) -      assert_received {:mix_shell, :info, [message]} -      assert message =~ "Deactivating" -        # Note that the task has delay :timer.sleep(500)        assert_received {:mix_shell, :info, [message]} -      assert message =~ "Successfully unsubscribed" + +      assert message == +               "Successfully deactivated #{user.nickname} and unsubscribed all local followers"        user = User.get_cached_by_nickname(user.nickname)        assert Enum.empty?(Enum.filter(User.get_friends(user), & &1.local)) -      assert user.deactivated +      refute user.is_active +    end + +    test "user is deactivated" do +      %{id: id, nickname: nickname} = insert(:user, is_active: false) + +      assert :ok = Mix.Tasks.Pleroma.User.run(["deactivate", nickname]) +      assert_received {:mix_shell, :info, [message]} +      assert message == "User #{nickname} already deactivated" + +      user = Repo.get(User, id) +      refute user.is_active      end      test "no user to deactivate" do @@ -238,7 +215,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do        assert message =~ ~r/Admin status .* true/        assert_received {:mix_shell, :info, [message]} -      assert message =~ ~r/Confirmation pending .* false/ +      assert message =~ ~r/Confirmation status.* true/        assert_received {:mix_shell, :info, [message]}        assert message =~ ~r/Locked status .* true/ @@ -250,7 +227,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do        assert user.is_moderator        assert user.is_locked        assert user.is_admin -      refute user.confirmation_pending +      assert user.is_confirmed      end      test "All statuses unset" do @@ -259,7 +236,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do            is_locked: true,            is_moderator: true,            is_admin: true, -          confirmation_pending: true +          is_confirmed: false          )        Mix.Tasks.Pleroma.User.run([ @@ -275,7 +252,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do        assert message =~ ~r/Admin status .* false/        assert_received {:mix_shell, :info, [message]} -      assert message =~ ~r/Confirmation pending .* true/ +      assert message =~ ~r/Confirmation status.* false/        assert_received {:mix_shell, :info, [message]}        assert message =~ ~r/Locked status .* false/ @@ -287,7 +264,7 @@ defmodule Mix.Tasks.Pleroma.UserTest do        refute user.is_moderator        refute user.is_locked        refute user.is_admin -      assert user.confirmation_pending +      refute user.is_confirmed      end      test "no user to set status" do @@ -436,13 +413,6 @@ defmodule Mix.Tasks.Pleroma.UserTest do        assert_received {:mix_shell, :info, [message]}        assert message =~ "Invite for token #{invite.token} was revoked."      end - -    test "it prints an error message when invite is not exist" do -      Mix.Tasks.Pleroma.User.run(["revoke_invite", "foo"]) - -      assert_received {:mix_shell, :error, [message]} -      assert message =~ "No invite found" -    end    end    describe "running delete_activities" do @@ -462,40 +432,71 @@ defmodule Mix.Tasks.Pleroma.UserTest do      end    end -  describe "running toggle_confirmed" do +  describe "running confirm" do      test "user is confirmed" do -      %{id: id, nickname: nickname} = insert(:user, confirmation_pending: false) +      %{id: id, nickname: nickname} = insert(:user, is_confirmed: true) -      assert :ok = Mix.Tasks.Pleroma.User.run(["toggle_confirmed", nickname]) +      assert :ok = Mix.Tasks.Pleroma.User.run(["confirm", nickname])        assert_received {:mix_shell, :info, [message]} -      assert message == "#{nickname} needs confirmation." +      assert message == "#{nickname} doesn't need confirmation."        user = Repo.get(User, id) -      assert user.confirmation_pending -      assert user.confirmation_token +      assert user.is_confirmed +      refute user.confirmation_token      end      test "user is not confirmed" do        %{id: id, nickname: nickname} = -        insert(:user, confirmation_pending: true, confirmation_token: "some token") +        insert(:user, is_confirmed: false, confirmation_token: "some token") -      assert :ok = Mix.Tasks.Pleroma.User.run(["toggle_confirmed", nickname]) +      assert :ok = Mix.Tasks.Pleroma.User.run(["confirm", nickname])        assert_received {:mix_shell, :info, [message]}        assert message == "#{nickname} doesn't need confirmation."        user = Repo.get(User, id) -      refute user.confirmation_pending +      assert user.is_confirmed        refute user.confirmation_token      end      test "it prints an error message when user is not exist" do -      Mix.Tasks.Pleroma.User.run(["toggle_confirmed", "foo"]) +      Mix.Tasks.Pleroma.User.run(["confirm", "foo"])        assert_received {:mix_shell, :error, [message]}        assert message =~ "No local user"      end    end +  describe "running activate" do +    test "user is activated" do +      %{id: id, nickname: nickname} = insert(:user, is_active: true) + +      assert :ok = Mix.Tasks.Pleroma.User.run(["activate", nickname]) +      assert_received {:mix_shell, :info, [message]} +      assert message == "User #{nickname} already activated" + +      user = Repo.get(User, id) +      assert user.is_active +    end + +    test "user is not activated" do +      %{id: id, nickname: nickname} = insert(:user, is_active: false) + +      assert :ok = Mix.Tasks.Pleroma.User.run(["activate", nickname]) +      assert_received {:mix_shell, :info, [message]} +      assert message == "Successfully activated #{nickname}" + +      user = Repo.get(User, id) +      assert user.is_active +    end + +    test "no user to activate" do +      Mix.Tasks.Pleroma.User.run(["activate", "foo"]) + +      assert_received {:mix_shell, :error, [message]} +      assert message =~ "No user" +    end +  end +    describe "search" do      test "it returns users matching" do        user = insert(:user) @@ -579,29 +580,29 @@ defmodule Mix.Tasks.Pleroma.UserTest do    describe "bulk confirm and unconfirm" do      test "confirm all" do -      user1 = insert(:user, confirmation_pending: true) -      user2 = insert(:user, confirmation_pending: true) +      user1 = insert(:user, is_confirmed: false) +      user2 = insert(:user, is_confirmed: false) -      assert user1.confirmation_pending -      assert user2.confirmation_pending +      refute user1.is_confirmed +      refute user2.is_confirmed        Mix.Tasks.Pleroma.User.run(["confirm_all"])        user1 = User.get_cached_by_nickname(user1.nickname)        user2 = User.get_cached_by_nickname(user2.nickname) -      refute user1.confirmation_pending -      refute user2.confirmation_pending +      assert user1.is_confirmed +      assert user2.is_confirmed      end      test "unconfirm all" do -      user1 = insert(:user, confirmation_pending: false) -      user2 = insert(:user, confirmation_pending: false) -      admin = insert(:user, is_admin: true, confirmation_pending: false) -      mod = insert(:user, is_moderator: true, confirmation_pending: false) +      user1 = insert(:user, is_confirmed: true) +      user2 = insert(:user, is_confirmed: true) +      admin = insert(:user, is_admin: true, is_confirmed: true) +      mod = insert(:user, is_moderator: true, is_confirmed: true) -      refute user1.confirmation_pending -      refute user2.confirmation_pending +      assert user1.is_confirmed +      assert user2.is_confirmed        Mix.Tasks.Pleroma.User.run(["unconfirm_all"]) @@ -610,10 +611,10 @@ defmodule Mix.Tasks.Pleroma.UserTest do        admin = User.get_cached_by_nickname(admin.nickname)        mod = User.get_cached_by_nickname(mod.nickname) -      assert user1.confirmation_pending -      assert user2.confirmation_pending -      refute admin.confirmation_pending -      refute mod.confirmation_pending +      refute user1.is_confirmed +      refute user2.is_confirmed +      assert admin.is_confirmed +      assert mod.is_confirmed      end    end  end diff --git a/test/pleroma/activity/ir/topics_test.exs b/test/pleroma/activity/ir/topics_test.exs index 5e5c2f8da..9c8e5d932 100644 --- a/test/pleroma/activity/ir/topics_test.exs +++ b/test/pleroma/activity/ir/topics_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Activity.Ir.TopicsTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.Activity.Ir.Topics @@ -11,6 +11,8 @@ defmodule Pleroma.Activity.Ir.TopicsTest do    require Pleroma.Constants +  import Mock +    describe "poll answer" do      test "produce no topics" do        activity = %Activity{object: %Object{data: %{"type" => "Answer"}}} @@ -77,14 +79,13 @@ defmodule Pleroma.Activity.Ir.TopicsTest do        refute Enum.member?(topics, "public:local:media")      end -    test "converts tags to hash tags", %{activity: %{object: %{data: data} = object} = activity} do -      tagged_data = Map.put(data, "tag", ["foo", "bar"]) -      activity = %{activity | object: %{object | data: tagged_data}} - -      topics = Topics.get_activity_topics(activity) +    test "converts tags to hash tags", %{activity: activity} do +      with_mock(Object, [:passthrough], hashtags: fn _ -> ["foo", "bar"] end) do +        topics = Topics.get_activity_topics(activity) -      assert Enum.member?(topics, "hashtag:foo") -      assert Enum.member?(topics, "hashtag:bar") +        assert Enum.member?(topics, "hashtag:foo") +        assert Enum.member?(topics, "hashtag:bar") +      end      end      test "only converts strings to hash tags", %{ diff --git a/test/pleroma/activity/search_test.exs b/test/pleroma/activity/search_test.exs index fc910e725..657fbc627 100644 --- a/test/pleroma/activity/search_test.exs +++ b/test/pleroma/activity/search_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Activity.SearchTest do @@ -7,7 +7,7 @@ defmodule Pleroma.Activity.SearchTest do    alias Pleroma.Web.CommonAPI    import Pleroma.Factory -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    test "it finds something" do      user = insert(:user) diff --git a/test/pleroma/activity_test.exs b/test/pleroma/activity_test.exs index 105f9f766..962bc7e45 100644 --- a/test/pleroma/activity_test.exs +++ b/test/pleroma/activity_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ActivityTest do @@ -25,7 +25,7 @@ defmodule Pleroma.ActivityTest do    test "returns activities by it's objects AP ids" do      activity = insert(:note_activity) -    object_data = Object.normalize(activity).data +    object_data = Object.normalize(activity, fetch: false).data      [found_activity] = Activity.get_all_create_by_object_ap_id(object_data["id"]) @@ -34,7 +34,7 @@ defmodule Pleroma.ActivityTest do    test "returns the activity that created an object" do      activity = insert(:note_activity) -    object_data = Object.normalize(activity).data +    object_data = Object.normalize(activity, fetch: false).data      found_activity = Activity.get_create_by_object_ap_id(object_data["id"]) @@ -168,7 +168,7 @@ defmodule Pleroma.ActivityTest do      test "find only local statuses for unauthenticated users  when `limit_to_local_content` is `:all`",           %{local_activity: local_activity} do -      Pleroma.Config.put([:instance, :limit_to_local_content], :all) +      clear_config([:instance, :limit_to_local_content], :all)        assert [^local_activity] = Activity.search(nil, "find me")      end @@ -177,7 +177,7 @@ defmodule Pleroma.ActivityTest do             local_activity: local_activity,             remote_activity: remote_activity           } do -      Pleroma.Config.put([:instance, :limit_to_local_content], false) +      clear_config([:instance, :limit_to_local_content], false)        activities = Enum.sort_by(Activity.search(nil, "find me"), & &1.id) @@ -254,4 +254,26 @@ defmodule Pleroma.ActivityTest do      assert %{id: ^id} = Activity.get_by_object_ap_id_with_object(obj_id)    end + +  test "add_by_params_query/3" do +    user = insert(:user) + +    note = insert(:note_activity, user: user) + +    insert(:add_activity, user: user, note: note) +    insert(:add_activity, user: user, note: note) +    insert(:add_activity, user: user) + +    assert Repo.aggregate(Activity, :count, :id) == 4 + +    add_query = +      Activity.add_by_params_query(note.data["object"], user.ap_id, user.featured_address) + +    assert Repo.aggregate(add_query, :count, :id) == 2 + +    Repo.delete_all(add_query) +    assert Repo.aggregate(add_query, :count, :id) == 0 + +    assert Repo.aggregate(Activity, :count, :id) == 2 +  end  end diff --git a/test/pleroma/application_requirements_test.exs b/test/pleroma/application_requirements_test.exs index b432dbc37..683ac8c96 100644 --- a/test/pleroma/application_requirements_test.exs +++ b/test/pleroma/application_requirements_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ApplicationRequirementsTest do @@ -9,12 +9,12 @@ defmodule Pleroma.ApplicationRequirementsTest do    import Mock    alias Pleroma.ApplicationRequirements -  alias Pleroma.Config    alias Pleroma.Repo    describe "check_repo_pool_size!/1" do      test "raises if the pool size is unexpected" do        clear_config([Pleroma.Repo, :pool_size], 11) +      clear_config([:dangerzone, :override_repo_pool_size], false)        assert_raise Pleroma.ApplicationRequirements.VerifyError,                     "Repo.pool_size different than recommended value.", @@ -36,8 +36,8 @@ defmodule Pleroma.ApplicationRequirementsTest do      setup do: clear_config([Pleroma.Emails.Mailer])      test "raises if welcome email enabled but mail disabled" do -      Pleroma.Config.put([:welcome, :email, :enabled], true) -      Pleroma.Config.put([Pleroma.Emails.Mailer, :enabled], false) +      clear_config([:welcome, :email, :enabled], true) +      clear_config([Pleroma.Emails.Mailer, :enabled], false)        assert_raise Pleroma.ApplicationRequirements.VerifyError, "The mail disabled.", fn ->          capture_log(&Pleroma.ApplicationRequirements.verify!/0) @@ -58,8 +58,8 @@ defmodule Pleroma.ApplicationRequirementsTest do      setup do: clear_config([:instance, :account_activation_required])      test "raises if account confirmation is required but mailer isn't enable" do -      Pleroma.Config.put([:instance, :account_activation_required], true) -      Pleroma.Config.put([Pleroma.Emails.Mailer, :enabled], false) +      clear_config([:instance, :account_activation_required], true) +      clear_config([Pleroma.Emails.Mailer, :enabled], false)        assert_raise Pleroma.ApplicationRequirements.VerifyError,                     "Account activation enabled, but Mailer is disabled. Cannot send confirmation emails.", @@ -69,14 +69,14 @@ defmodule Pleroma.ApplicationRequirementsTest do      end      test "doesn't do anything if account confirmation is disabled" do -      Pleroma.Config.put([:instance, :account_activation_required], false) -      Pleroma.Config.put([Pleroma.Emails.Mailer, :enabled], false) +      clear_config([:instance, :account_activation_required], false) +      clear_config([Pleroma.Emails.Mailer, :enabled], false)        assert Pleroma.ApplicationRequirements.verify!() == :ok      end      test "doesn't do anything if account confirmation is required and mailer is enabled" do -      Pleroma.Config.put([:instance, :account_activation_required], true) -      Pleroma.Config.put([Pleroma.Emails.Mailer, :enabled], true) +      clear_config([:instance, :account_activation_required], true) +      clear_config([Pleroma.Emails.Mailer, :enabled], true)        assert Pleroma.ApplicationRequirements.verify!() == :ok      end    end @@ -92,7 +92,7 @@ defmodule Pleroma.ApplicationRequirementsTest do      setup do: clear_config([:database, :rum_enabled])      test "raises if rum is enabled and detects unapplied rum migrations" do -      Config.put([:database, :rum_enabled], true) +      clear_config([:database, :rum_enabled], true)        with_mocks([{Repo, [:passthrough], [exists?: fn _, _ -> false end]}]) do          assert_raise ApplicationRequirements.VerifyError, @@ -104,7 +104,7 @@ defmodule Pleroma.ApplicationRequirementsTest do      end      test "raises if rum is disabled and detects rum migrations" do -      Config.put([:database, :rum_enabled], false) +      clear_config([:database, :rum_enabled], false)        with_mocks([{Repo, [:passthrough], [exists?: fn _, _ -> true end]}]) do          assert_raise ApplicationRequirements.VerifyError, @@ -116,7 +116,7 @@ defmodule Pleroma.ApplicationRequirementsTest do      end      test "doesn't do anything if rum enabled and applied migrations" do -      Config.put([:database, :rum_enabled], true) +      clear_config([:database, :rum_enabled], true)        with_mocks([{Repo, [:passthrough], [exists?: fn _, _ -> true end]}]) do          assert ApplicationRequirements.verify!() == :ok @@ -124,7 +124,7 @@ defmodule Pleroma.ApplicationRequirementsTest do      end      test "doesn't do anything if rum disabled" do -      Config.put([:database, :rum_enabled], false) +      clear_config([:database, :rum_enabled], false)        with_mocks([{Repo, [:passthrough], [exists?: fn _, _ -> false end]}]) do          assert ApplicationRequirements.verify!() == :ok @@ -160,7 +160,7 @@ defmodule Pleroma.ApplicationRequirementsTest do      end      test "doesn't do anything if disabled" do -      Config.put([:i_am_aware_this_may_cause_data_loss, :disable_migration_check], true) +      clear_config([:i_am_aware_this_may_cause_data_loss, :disable_migration_check], true)        assert :ok == ApplicationRequirements.verify!()      end diff --git a/test/pleroma/bbs/handler_test.exs b/test/pleroma/bbs/handler_test.exs index e605c2726..3990f8286 100644 --- a/test/pleroma/bbs/handler_test.exs +++ b/test/pleroma/bbs/handler_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.BBS.HandlerTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.BBS.Handler    alias Pleroma.Object @@ -54,7 +54,7 @@ defmodule Pleroma.BBS.HandlerTest do        )      assert activity.actor == user.ap_id -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert object.data["content"] == "this is a test post"    end @@ -63,7 +63,7 @@ defmodule Pleroma.BBS.HandlerTest do      another_user = insert(:user)      {:ok, activity} = CommonAPI.post(another_user, %{status: "this is a test post"}) -    activity_object = Object.normalize(activity) +    activity_object = Object.normalize(activity, fetch: false)      output =        capture_io(fn -> @@ -82,7 +82,7 @@ defmodule Pleroma.BBS.HandlerTest do      assert reply.actor == user.ap_id -    reply_object_data = Object.normalize(reply).data +    reply_object_data = Object.normalize(reply, fetch: false).data      assert reply_object_data["content"] == "this is a reply"      assert reply_object_data["inReplyTo"] == activity_object.data["id"]    end diff --git a/test/pleroma/bookmark_test.exs b/test/pleroma/bookmark_test.exs index 2726fe7cd..9f64a01c2 100644 --- a/test/pleroma/bookmark_test.exs +++ b/test/pleroma/bookmark_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.BookmarkTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Bookmark    alias Pleroma.Web.CommonAPI diff --git a/test/pleroma/captcha_test.exs b/test/pleroma/captcha_test.exs index 1b9f4a12f..fcb585112 100644 --- a/test/pleroma/captcha_test.exs +++ b/test/pleroma/captcha_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.CaptchaTest do @@ -69,7 +69,7 @@ defmodule Pleroma.CaptchaTest do    describe "Captcha Wrapper" do      test "validate" do -      Pleroma.Config.put([Pleroma.Captcha, :enabled], true) +      clear_config([Pleroma.Captcha, :enabled], true)        new = Captcha.new() @@ -80,11 +80,10 @@ defmodule Pleroma.CaptchaTest do        assert is_binary(answer)        assert :ok = Captcha.validate(token, "63615261b77f5354fb8c4e4986477555", answer) -      Cachex.del(:used_captcha_cache, token)      end      test "doesn't validate invalid answer" do -      Pleroma.Config.put([Pleroma.Captcha, :enabled], true) +      clear_config([Pleroma.Captcha, :enabled], true)        new = Captcha.new() @@ -100,7 +99,7 @@ defmodule Pleroma.CaptchaTest do      end      test "nil answer_data" do -      Pleroma.Config.put([Pleroma.Captcha, :enabled], true) +      clear_config([Pleroma.Captcha, :enabled], true)        new = Captcha.new() diff --git a/test/pleroma/chat/message_reference_test.exs b/test/pleroma/chat/message_reference_test.exs index aaa7c1ad4..c8db3b450 100644 --- a/test/pleroma/chat/message_reference_test.exs +++ b/test/pleroma/chat/message_reference_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Chat.MessageReferenceTest do diff --git a/test/pleroma/chat_test.exs b/test/pleroma/chat_test.exs index 9e8a9ebf0..a5fd1e02e 100644 --- a/test/pleroma/chat_test.exs +++ b/test/pleroma/chat_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ChatTest do @@ -73,7 +73,8 @@ defmodule Pleroma.ChatTest do        other_user = insert(:user)        {:ok, chat} = Chat.bump_or_create(user.id, other_user.ap_id) -      :timer.sleep(1500) +      {:ok, chat} = time_travel(chat, -2) +        {:ok, chat_two} = Chat.bump_or_create(user.id, other_user.ap_id)        assert chat.id == chat_two.id diff --git a/test/pleroma/config/deprecation_warnings_test.exs b/test/pleroma/config/deprecation_warnings_test.exs index f52629f8a..15f4982ea 100644 --- a/test/pleroma/config/deprecation_warnings_test.exs +++ b/test/pleroma/config/deprecation_warnings_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Config.DeprecationWarningsTest do @@ -87,13 +87,22 @@ defmodule Pleroma.Config.DeprecationWarningsTest do    end    test "check_activity_expiration_config/0" do -    clear_config(Pleroma.ActivityExpiration, enabled: true) +    clear_config([Pleroma.ActivityExpiration], enabled: true)      assert capture_log(fn ->               DeprecationWarnings.check_activity_expiration_config()             end) =~ "Your config is using old namespace for activity expiration configuration."    end +  test "check_uploders_s3_public_endpoint/0" do +    clear_config([Pleroma.Uploaders.S3], public_endpoint: "https://fake.amazonaws.com/bucket/") + +    assert capture_log(fn -> +             DeprecationWarnings.check_uploders_s3_public_endpoint() +           end) =~ +             "Your config is using the old setting for controlling the URL of media uploaded to your S3 bucket." +  end +    describe "check_gun_pool_options/0" do      test "await_up_timeout" do        config = Config.get(:connections_pool) diff --git a/test/pleroma/config/holder_test.exs b/test/pleroma/config/holder_test.exs index abcaa27dd..ca4c38995 100644 --- a/test/pleroma/config/holder_test.exs +++ b/test/pleroma/config/holder_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Config.HolderTest do diff --git a/test/pleroma/config/loader_test.exs b/test/pleroma/config/loader_test.exs index 607572f4e..b34fd70da 100644 --- a/test/pleroma/config/loader_test.exs +++ b/test/pleroma/config/loader_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Config.LoaderTest do diff --git a/test/pleroma/config/release_runtime_provider_test.exs b/test/pleroma/config/release_runtime_provider_test.exs new file mode 100644 index 000000000..6578d3268 --- /dev/null +++ b/test/pleroma/config/release_runtime_provider_test.exs @@ -0,0 +1,45 @@ +defmodule Pleroma.Config.ReleaseRuntimeProviderTest do +  use ExUnit.Case, async: true + +  alias Pleroma.Config.ReleaseRuntimeProvider + +  describe "load/2" do +    test "loads release defaults config and warns about non-existent runtime config" do +      ExUnit.CaptureIO.capture_io(fn -> +        merged = ReleaseRuntimeProvider.load([], []) +        assert merged == Pleroma.Config.Holder.release_defaults() +      end) =~ +        "!!! Config path is not declared! Please ensure it exists and that PLEROMA_CONFIG_PATH is unset or points to an existing file" +    end + +    test "merged runtime config" do +      merged = +        ReleaseRuntimeProvider.load([], config_path: "test/fixtures/config/temp.secret.exs") + +      assert merged[:pleroma][:first_setting] == [key: "value", key2: [Pleroma.Repo]] +      assert merged[:pleroma][:second_setting] == [key: "value2", key2: ["Activity"]] +    end + +    test "merged exported config" do +      ExUnit.CaptureIO.capture_io(fn -> +        merged = +          ReleaseRuntimeProvider.load([], +            exported_config_path: "test/fixtures/config/temp.exported_from_db.secret.exs" +          ) + +        assert merged[:pleroma][:exported_config_merged] +      end) =~ +        "!!! Config path is not declared! Please ensure it exists and that PLEROMA_CONFIG_PATH is unset or points to an existing file" +    end + +    test "runtime config is merged with exported config" do +      merged = +        ReleaseRuntimeProvider.load([], +          config_path: "test/fixtures/config/temp.secret.exs", +          exported_config_path: "test/fixtures/config/temp.exported_from_db.secret.exs" +        ) + +      assert merged[:pleroma][:first_setting] == [key2: [Pleroma.Repo], key: "new value"] +    end +  end +end diff --git a/test/pleroma/config/transfer_task_test.exs b/test/pleroma/config/transfer_task_test.exs index f53829e09..8ae5d3b81 100644 --- a/test/pleroma/config/transfer_task_test.exs +++ b/test/pleroma/config/transfer_task_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Config.TransferTaskTest do diff --git a/test/pleroma/config_db_test.exs b/test/pleroma/config_db_test.exs index 3895e2cda..d42123fb4 100644 --- a/test/pleroma/config_db_test.exs +++ b/test/pleroma/config_db_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ConfigDBTest do diff --git a/test/pleroma/config_test.exs b/test/pleroma/config_test.exs index 1556e4237..3158a2ec8 100644 --- a/test/pleroma/config_test.exs +++ b/test/pleroma/config_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ConfigTest do -  use ExUnit.Case +  use Pleroma.DataCase    test "get/1 with an atom" do      assert Pleroma.Config.get(:instance) == Application.get_env(:pleroma, :instance) @@ -30,9 +30,9 @@ defmodule Pleroma.ConfigTest do    describe "nil values" do      setup do -      Pleroma.Config.put(:lorem, nil) -      Pleroma.Config.put(:ipsum, %{dolor: [sit: nil]}) -      Pleroma.Config.put(:dolor, sit: %{amet: nil}) +      clear_config(:lorem, nil) +      clear_config(:ipsum, %{dolor: [sit: nil]}) +      clear_config(:dolor, sit: %{amet: nil})        on_exit(fn -> Enum.each(~w(lorem ipsum dolor)a, &Pleroma.Config.delete/1) end)      end @@ -57,9 +57,9 @@ defmodule Pleroma.ConfigTest do    end    test "get/1 when value is false" do -    Pleroma.Config.put([:instance, :false_test], false) -    Pleroma.Config.put([:instance, :nested], []) -    Pleroma.Config.put([:instance, :nested, :false_test], false) +    clear_config([:instance, :false_test], false) +    clear_config([:instance, :nested], []) +    clear_config([:instance, :nested, :false_test], false)      assert Pleroma.Config.get([:instance, :false_test]) == false      assert Pleroma.Config.get([:instance, :nested, :false_test]) == false @@ -81,40 +81,40 @@ defmodule Pleroma.ConfigTest do    end    test "get!/1 when value is false" do -    Pleroma.Config.put([:instance, :false_test], false) -    Pleroma.Config.put([:instance, :nested], []) -    Pleroma.Config.put([:instance, :nested, :false_test], false) +    clear_config([:instance, :false_test], false) +    clear_config([:instance, :nested], []) +    clear_config([:instance, :nested, :false_test], false)      assert Pleroma.Config.get!([:instance, :false_test]) == false      assert Pleroma.Config.get!([:instance, :nested, :false_test]) == false    end    test "put/2 with a key" do -    Pleroma.Config.put(:config_test, true) +    clear_config(:config_test, true)      assert Pleroma.Config.get(:config_test) == true    end    test "put/2 with a list of keys" do -    Pleroma.Config.put([:instance, :config_test], true) -    Pleroma.Config.put([:instance, :config_nested_test], []) -    Pleroma.Config.put([:instance, :config_nested_test, :x], true) +    clear_config([:instance, :config_test], true) +    clear_config([:instance, :config_nested_test], []) +    clear_config([:instance, :config_nested_test, :x], true)      assert Pleroma.Config.get([:instance, :config_test]) == true      assert Pleroma.Config.get([:instance, :config_nested_test, :x]) == true    end    test "delete/1 with a key" do -    Pleroma.Config.put([:delete_me], :delete_me) +    clear_config([:delete_me], :delete_me)      Pleroma.Config.delete([:delete_me])      assert Pleroma.Config.get([:delete_me]) == nil    end    test "delete/2 with a list of keys" do -    Pleroma.Config.put([:delete_me], hello: "world", world: "Hello") +    clear_config([:delete_me], hello: "world", world: "Hello")      Pleroma.Config.delete([:delete_me, :world])      assert Pleroma.Config.get([:delete_me]) == [hello: "world"] -    Pleroma.Config.put([:delete_me, :delete_me], hello: "world", world: "Hello") +    clear_config([:delete_me, :delete_me], hello: "world", world: "Hello")      Pleroma.Config.delete([:delete_me, :delete_me, :world])      assert Pleroma.Config.get([:delete_me, :delete_me]) == [hello: "world"] @@ -123,8 +123,8 @@ defmodule Pleroma.ConfigTest do    end    test "fetch/1" do -    Pleroma.Config.put([:lorem], :ipsum) -    Pleroma.Config.put([:ipsum], dolor: :sit) +    clear_config([:lorem], :ipsum) +    clear_config([:ipsum], dolor: :sit)      assert Pleroma.Config.fetch([:lorem]) == {:ok, :ipsum}      assert Pleroma.Config.fetch(:lorem) == {:ok, :ipsum} diff --git a/test/pleroma/conversation/participation_test.exs b/test/pleroma/conversation/participation_test.exs index 5a603dcc1..a25e17c95 100644 --- a/test/pleroma/conversation/participation_test.exs +++ b/test/pleroma/conversation/participation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Conversation.ParticipationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Conversation    alias Pleroma.Conversation.Participation @@ -96,12 +96,11 @@ defmodule Pleroma.Conversation.ParticipationTest do      {:ok, %Participation{} = participation} =        Participation.create_for_user_and_conversation(user, conversation) +    {:ok, participation} = time_travel(participation, -2) +      assert participation.user_id == user.id      assert participation.conversation_id == conversation.id -    # Needed because updated_at is accurate down to a second -    :timer.sleep(1000) -      # Creating again returns the same participation      {:ok, %Participation{} = participation_two} =        Participation.create_for_user_and_conversation(user, conversation) @@ -176,8 +175,8 @@ defmodule Pleroma.Conversation.ParticipationTest do      assert [participation_one, participation_two] = Participation.for_user(user) -    object2 = Pleroma.Object.normalize(activity_two) -    object3 = Pleroma.Object.normalize(activity_three) +    object2 = Pleroma.Object.normalize(activity_two, fetch: false) +    object3 = Pleroma.Object.normalize(activity_three, fetch: false)      user = Repo.get(Pleroma.User, user.id) @@ -360,4 +359,16 @@ defmodule Pleroma.Conversation.ParticipationTest do        assert Participation.unread_count(blocked) == 1      end    end + +  test "deletes a conversation" do +    user = insert(:user) +    other_user = insert(:user) + +    {:ok, _activity} = +      CommonAPI.post(user, %{status: "Hey @#{other_user.nickname}.", visibility: "direct"}) + +    assert [participation] = Participation.for_user(other_user) +    assert {:ok, _} = Participation.delete(participation) +    assert [] == Participation.for_user(other_user) +  end  end diff --git a/test/pleroma/conversation_test.exs b/test/pleroma/conversation_test.exs index 359aa6840..1a947606d 100644 --- a/test/pleroma/conversation_test.exs +++ b/test/pleroma/conversation_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ConversationTest do @@ -48,7 +48,7 @@ defmodule Pleroma.ConversationTest do      user = insert(:user)      {:ok, activity} = CommonAPI.post(user, %{status: "Hey"}) -    object = Pleroma.Object.normalize(activity) +    object = Pleroma.Object.normalize(activity, fetch: false)      context = object.data["context"]      conversation = Conversation.get_for_ap_id(context) @@ -64,7 +64,7 @@ defmodule Pleroma.ConversationTest do      {:ok, activity} =        CommonAPI.post(har, %{status: "Hey @#{jafnhar.nickname}", visibility: "direct"}) -    object = Pleroma.Object.normalize(activity) +    object = Pleroma.Object.normalize(activity, fetch: false)      context = object.data["context"]      conversation = @@ -86,7 +86,7 @@ defmodule Pleroma.ConversationTest do          in_reply_to_status_id: activity.id        }) -    object = Pleroma.Object.normalize(activity) +    object = Pleroma.Object.normalize(activity, fetch: false)      context = object.data["context"]      conversation_two = @@ -110,7 +110,7 @@ defmodule Pleroma.ConversationTest do          in_reply_to_status_id: activity.id        }) -    object = Pleroma.Object.normalize(activity) +    object = Pleroma.Object.normalize(activity, fetch: false)      context = object.data["context"]      conversation_three = diff --git a/test/pleroma/docs/generator_test.exs b/test/pleroma/docs/generator_test.exs index 43877244d..a9b09e577 100644 --- a/test/pleroma/docs/generator_test.exs +++ b/test/pleroma/docs/generator_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Docs.GeneratorTest do diff --git a/test/pleroma/ecto_type/activity_pub/object_validators/date_time_test.exs b/test/pleroma/ecto_type/activity_pub/object_validators/date_time_test.exs index 812463454..259fd6a5f 100644 --- a/test/pleroma/ecto_type/activity_pub/object_validators/date_time_test.exs +++ b/test/pleroma/ecto_type/activity_pub/object_validators/date_time_test.exs @@ -1,10 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.EctoType.ActivityPub.ObjectValidators.DateTimeTest do    alias Pleroma.EctoType.ActivityPub.ObjectValidators.DateTime -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    test "it validates an xsd:Datetime" do      valid_strings = [ diff --git a/test/pleroma/ecto_type/activity_pub/object_validators/object_id_test.exs b/test/pleroma/ecto_type/activity_pub/object_validators/object_id_test.exs index 732e2365f..1a4c2dfcb 100644 --- a/test/pleroma/ecto_type/activity_pub/object_validators/object_id_test.exs +++ b/test/pleroma/ecto_type/activity_pub/object_validators/object_id_test.exs @@ -1,10 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.EctoType.ActivityPub.ObjectValidators.ObjectIDTest do    alias Pleroma.EctoType.ActivityPub.ObjectValidators.ObjectID -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    @uris [      "http://lain.com/users/lain", diff --git a/test/pleroma/ecto_type/activity_pub/object_validators/recipients_test.exs b/test/pleroma/ecto_type/activity_pub/object_validators/recipients_test.exs index 2e6a0c83d..d3a2fd13f 100644 --- a/test/pleroma/ecto_type/activity_pub/object_validators/recipients_test.exs +++ b/test/pleroma/ecto_type/activity_pub/object_validators/recipients_test.exs @@ -1,10 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.EctoType.ActivityPub.ObjectValidators.RecipientsTest do    alias Pleroma.EctoType.ActivityPub.ObjectValidators.Recipients -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    test "it asserts that all elements of the list are object ids" do      list = ["https://lain.com/users/lain", "invalid"] diff --git a/test/pleroma/ecto_type/activity_pub/object_validators/safe_text_test.exs b/test/pleroma/ecto_type/activity_pub/object_validators/safe_text_test.exs index 7eddd2388..7002eca30 100644 --- a/test/pleroma/ecto_type/activity_pub/object_validators/safe_text_test.exs +++ b/test/pleroma/ecto_type/activity_pub/object_validators/safe_text_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.EctoType.ActivityPub.ObjectValidators.SafeTextTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.EctoType.ActivityPub.ObjectValidators.SafeText diff --git a/test/pleroma/emails/admin_email_test.exs b/test/pleroma/emails/admin_email_test.exs index 0da0699cc..04c907697 100644 --- a/test/pleroma/emails/admin_email_test.exs +++ b/test/pleroma/emails/admin_email_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Emails.AdminEmailTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Emails.AdminEmail diff --git a/test/pleroma/emails/mailer_test.exs b/test/pleroma/emails/mailer_test.exs index 9e232d2a0..a8e1553e5 100644 --- a/test/pleroma/emails/mailer_test.exs +++ b/test/pleroma/emails/mailer_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Emails.MailerTest do diff --git a/test/pleroma/emails/user_email_test.exs b/test/pleroma/emails/user_email_test.exs index a75623bb4..21fd06ea6 100644 --- a/test/pleroma/emails/user_email_test.exs +++ b/test/pleroma/emails/user_email_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Emails.UserEmailTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Emails.UserEmail    alias Pleroma.Web.Endpoint @@ -45,4 +45,15 @@ defmodule Pleroma.Emails.UserEmailTest do      assert email.html_body =~               Router.Helpers.confirm_email_url(Endpoint, :confirm_email, user.id, "conf-token")    end + +  test "build approval pending email" do +    config = Pleroma.Config.get(:instance) +    user = insert(:user) +    email = UserEmail.approval_pending_email(user) + +    assert email.from == {config[:name], config[:notify_email]} +    assert email.to == [{user.name, user.email}] +    assert email.subject == "Your account is awaiting approval" +    assert email.html_body =~ "Awaiting Approval" +  end  end diff --git a/test/pleroma/emoji/formatter_test.exs b/test/pleroma/emoji/formatter_test.exs index 12af6cd8b..3942f609f 100644 --- a/test/pleroma/emoji/formatter_test.exs +++ b/test/pleroma/emoji/formatter_test.exs @@ -1,10 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Emoji.FormatterTest do    alias Pleroma.Emoji.Formatter -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    describe "emojify" do      test "it adds cool emoji" do diff --git a/test/pleroma/emoji/loader_test.exs b/test/pleroma/emoji/loader_test.exs index 804039e7e..de89e3bc4 100644 --- a/test/pleroma/emoji/loader_test.exs +++ b/test/pleroma/emoji/loader_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Emoji.LoaderTest do diff --git a/test/pleroma/emoji/pack_test.exs b/test/pleroma/emoji/pack_test.exs index 70d1eaa1b..ac7535412 100644 --- a/test/pleroma/emoji/pack_test.exs +++ b/test/pleroma/emoji/pack_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Emoji.PackTest do -  use ExUnit.Case, async: true +  use Pleroma.DataCase    alias Pleroma.Emoji.Pack    @emoji_path Path.join( diff --git a/test/pleroma/emoji_test.exs b/test/pleroma/emoji_test.exs index 9cfd7b46b..027a8132f 100644 --- a/test/pleroma/emoji_test.exs +++ b/test/pleroma/emoji_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.EmojiTest do -  use ExUnit.Case +  use ExUnit.Case, async: true    alias Pleroma.Emoji    describe "is_unicode_emoji?/1" do diff --git a/test/pleroma/filter_test.exs b/test/pleroma/filter_test.exs index 0a5c4426a..19ad6b8c0 100644 --- a/test/pleroma/filter_test.exs +++ b/test/pleroma/filter_test.exs @@ -1,87 +1,126 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.FilterTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory +  alias Oban.Job    alias Pleroma.Filter -  alias Pleroma.Repo + +  setup do +    [user: insert(:user)] +  end    describe "creating filters" do -    test "creating one filter" do -      user = insert(:user) +    test "creation validation error", %{user: user} do +      attrs = %{ +        user_id: user.id, +        expires_in: 60 +      } + +      {:error, _} = Filter.create(attrs) + +      assert Repo.all(Job) == [] +    end -      query = %Filter{ +    test "use passed expires_at instead expires_in", %{user: user} do +      now = NaiveDateTime.utc_now() + +      attrs = %{          user_id: user.id, -        filter_id: 42, +        expires_at: now,          phrase: "knights", -        context: ["home"] +        context: ["home"], +        expires_in: 600        } -      {:ok, %Filter{} = filter} = Filter.create(query) +      {:ok, %Filter{} = filter} = Filter.create(attrs) +        result = Filter.get(filter.filter_id, user) -      assert query.phrase == result.phrase -    end +      assert result.expires_at == NaiveDateTime.truncate(now, :second) -    test "creating one filter without a pre-defined filter_id" do -      user = insert(:user) +      [job] = Repo.all(Job) -      query = %Filter{ +      assert DateTime.truncate(job.scheduled_at, :second) == +               now |> NaiveDateTime.truncate(:second) |> DateTime.from_naive!("Etc/UTC") +    end + +    test "creating one filter", %{user: user} do +      attrs = %{          user_id: user.id, +        filter_id: 42,          phrase: "knights",          context: ["home"]        } -      {:ok, %Filter{} = filter} = Filter.create(query) -      # Should start at 1 -      assert filter.filter_id == 1 +      {:ok, %Filter{} = filter} = Filter.create(attrs) +      result = Filter.get(filter.filter_id, user) +      assert attrs.phrase == result.phrase      end -    test "creating additional filters uses previous highest filter_id + 1" do -      user = insert(:user) - -      query_one = %Filter{ +    test "creating with expired_at", %{user: user} do +      attrs = %{          user_id: user.id,          filter_id: 42,          phrase: "knights", +        context: ["home"], +        expires_in: 60 +      } + +      {:ok, %Filter{} = filter} = Filter.create(attrs) +      result = Filter.get(filter.filter_id, user) +      assert attrs.phrase == result.phrase + +      assert [_] = Repo.all(Job) +    end + +    test "creating one filter without a pre-defined filter_id", %{user: user} do +      attrs = %{ +        user_id: user.id, +        phrase: "knights",          context: ["home"]        } -      {:ok, %Filter{} = filter_one} = Filter.create(query_one) +      {:ok, %Filter{} = filter} = Filter.create(attrs) +      # Should start at 1 +      assert filter.filter_id == 1 +    end + +    test "creating additional filters uses previous highest filter_id + 1", %{user: user} do +      filter1 = insert(:filter, user: user) -      query_two = %Filter{ +      attrs = %{          user_id: user.id,          # No filter_id          phrase: "who",          context: ["home"]        } -      {:ok, %Filter{} = filter_two} = Filter.create(query_two) -      assert filter_two.filter_id == filter_one.filter_id + 1 +      {:ok, %Filter{} = filter2} = Filter.create(attrs) +      assert filter2.filter_id == filter1.filter_id + 1      end -    test "filter_id is unique per user" do -      user_one = insert(:user) +    test "filter_id is unique per user", %{user: user_one} do        user_two = insert(:user) -      query_one = %Filter{ +      attrs1 = %{          user_id: user_one.id,          phrase: "knights",          context: ["home"]        } -      {:ok, %Filter{} = filter_one} = Filter.create(query_one) +      {:ok, %Filter{} = filter_one} = Filter.create(attrs1) -      query_two = %Filter{ +      attrs2 = %{          user_id: user_two.id,          phrase: "who",          context: ["home"]        } -      {:ok, %Filter{} = filter_two} = Filter.create(query_two) +      {:ok, %Filter{} = filter_two} = Filter.create(attrs2)        assert filter_one.filter_id == 1        assert filter_two.filter_id == 1 @@ -94,65 +133,61 @@ defmodule Pleroma.FilterTest do      end    end -  test "deleting a filter" do -    user = insert(:user) +  test "deleting a filter", %{user: user} do +    filter = insert(:filter, user: user) -    query = %Filter{ -      user_id: user.id, -      filter_id: 0, -      phrase: "knights", -      context: ["home"] -    } - -    {:ok, _filter} = Filter.create(query) -    {:ok, filter} = Filter.delete(query) -    assert is_nil(Repo.get(Filter, filter.filter_id)) +    assert Repo.get(Filter, filter.id) +    {:ok, filter} = Filter.delete(filter) +    refute Repo.get(Filter, filter.id)    end -  test "getting all filters by an user" do -    user = insert(:user) - -    query_one = %Filter{ +  test "deleting a filter with expires_at is removing Oban job too", %{user: user} do +    attrs = %{        user_id: user.id, -      filter_id: 1, -      phrase: "knights", -      context: ["home"] +      phrase: "cofe", +      context: ["home"], +      expires_in: 600      } -    query_two = %Filter{ -      user_id: user.id, -      filter_id: 2, -      phrase: "who", -      context: ["home"] -    } +    {:ok, filter} = Filter.create(attrs) +    assert %Job{id: job_id} = Pleroma.Workers.PurgeExpiredFilter.get_expiration(filter.id) +    {:ok, _} = Filter.delete(filter) -    {:ok, filter_one} = Filter.create(query_one) -    {:ok, filter_two} = Filter.create(query_two) -    filters = Filter.get_filters(user) -    assert filter_one in filters -    assert filter_two in filters +    assert Repo.get(Job, job_id) == nil    end -  test "updating a filter" do -    user = insert(:user) +  test "getting all filters by an user", %{user: user} do +    filter1 = insert(:filter, user: user) +    filter2 = insert(:filter, user: user) -    query_one = %Filter{ -      user_id: user.id, -      filter_id: 1, -      phrase: "knights", -      context: ["home"] -    } +    filter_ids = user |> Filter.get_filters() |> collect_ids() + +    assert filter1.id in filter_ids +    assert filter2.id in filter_ids +  end + +  test "updating a filter", %{user: user} do +    filter = insert(:filter, user: user)      changes = %{        phrase: "who",        context: ["home", "timeline"]      } -    {:ok, filter_one} = Filter.create(query_one) -    {:ok, filter_two} = Filter.update(filter_one, changes) +    {:ok, updated_filter} = Filter.update(filter, changes) + +    assert filter != updated_filter +    assert updated_filter.phrase == changes.phrase +    assert updated_filter.context == changes.context +  end + +  test "updating with error", %{user: user} do +    filter = insert(:filter, user: user) + +    changes = %{ +      phrase: nil +    } -    assert filter_one != filter_two -    assert filter_two.phrase == changes.phrase -    assert filter_two.context == changes.context +    {:error, _} = Filter.update(filter, changes)    end  end diff --git a/test/pleroma/following_relationship_test.exs b/test/pleroma/following_relationship_test.exs index 17a468abb..37452996b 100644 --- a/test/pleroma/following_relationship_test.exs +++ b/test/pleroma/following_relationship_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.FollowingRelationshipTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.FollowingRelationship    alias Pleroma.Web.ActivityPub.InternalFetchActor diff --git a/test/pleroma/formatter_test.exs b/test/pleroma/formatter_test.exs index 5781a3f01..7f54638fb 100644 --- a/test/pleroma/formatter_test.exs +++ b/test/pleroma/formatter_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.FormatterTest do diff --git a/test/pleroma/frontend_test.exs b/test/pleroma/frontend_test.exs index 223625857..1b50a031d 100644 --- a/test/pleroma/frontend_test.exs +++ b/test/pleroma/frontend_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.FrontendTest do diff --git a/test/pleroma/gun/connection_pool_test.exs b/test/pleroma/gun/connection_pool_test.exs index aea908fac..4b3158625 100644 --- a/test/pleroma/gun/connection_pool_test.exs +++ b/test/pleroma/gun/connection_pool_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Gun.ConnectionPoolTest do @@ -7,7 +7,6 @@ defmodule Pleroma.Gun.ConnectionPoolTest do    import Mox    import ExUnit.CaptureLog -  alias Pleroma.Config    alias Pleroma.Gun.ConnectionPool    defp gun_mock(_) do @@ -19,7 +18,6 @@ defmodule Pleroma.Gun.ConnectionPoolTest do      :ok    end -  setup :set_mox_from_context    setup :gun_mock    test "gives the same connection to 2 concurrent requests" do @@ -50,7 +48,7 @@ defmodule Pleroma.Gun.ConnectionPoolTest do    test "connection limit is respected with concurrent requests" do      clear_config([:connections_pool, :max_connections]) do -      Config.put([:connections_pool, :max_connections], 1) +      clear_config([:connections_pool, :max_connections], 1)        # The supervisor needs a reboot to apply the new config setting        Process.exit(Process.whereis(Pleroma.Gun.ConnectionPool.WorkerSupervisor), :kill) diff --git a/test/pleroma/hashtag_test.exs b/test/pleroma/hashtag_test.exs new file mode 100644 index 000000000..0264dea0b --- /dev/null +++ b/test/pleroma/hashtag_test.exs @@ -0,0 +1,17 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.HashtagTest do +  use Pleroma.DataCase + +  alias Pleroma.Hashtag + +  describe "changeset validations" do +    test "ensure non-blank :name" do +      changeset = Hashtag.changeset(%Hashtag{}, %{name: ""}) + +      assert {:name, {"can't be blank", [validation: :required]}} in changeset.errors +    end +  end +end diff --git a/test/pleroma/healthcheck_test.exs b/test/pleroma/healthcheck_test.exs index e341e6983..469e5b397 100644 --- a/test/pleroma/healthcheck_test.exs +++ b/test/pleroma/healthcheck_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HealthcheckTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Healthcheck    test "system_info/0" do diff --git a/test/pleroma/html_test.exs b/test/pleroma/html_test.exs index 7d3756884..fe1a1ed57 100644 --- a/test/pleroma/html_test.exs +++ b/test/pleroma/html_test.exs @@ -1,12 +1,12 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTMLTest do    alias Pleroma.HTML    alias Pleroma.Object    alias Pleroma.Web.CommonAPI -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory @@ -175,7 +175,7 @@ defmodule Pleroma.HTMLTest do              "I think I just found the best github repo https://github.com/komeiji-satori/Dress"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        {:ok, url} = HTML.extract_first_external_url_from_object(object)        assert url == "https://github.com/komeiji-satori/Dress"      end @@ -190,7 +190,7 @@ defmodule Pleroma.HTMLTest do              "@#{other_user.nickname} install misskey! https://github.com/syuilo/misskey/blob/develop/docs/setup.en.md"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        {:ok, url} = HTML.extract_first_external_url_from_object(object)        assert url == "https://github.com/syuilo/misskey/blob/develop/docs/setup.en.md" @@ -206,7 +206,7 @@ defmodule Pleroma.HTMLTest do            status: "#cofe https://www.pixiv.net/member_illust.php?mode=medium&illust_id=72255140"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        {:ok, url} = HTML.extract_first_external_url_from_object(object)        assert url == "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=72255140" @@ -222,7 +222,7 @@ defmodule Pleroma.HTMLTest do            content_type: "text/html"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        {:ok, url} = HTML.extract_first_external_url_from_object(object)        assert url == "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=72255140" @@ -233,7 +233,7 @@ defmodule Pleroma.HTMLTest do        {:ok, activity} = CommonAPI.post(user, %{status: "\"http://cofe.com/?boomer=ok&foo=bar\""}) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert {:ok, nil} = HTML.extract_first_external_url_from_object(object)      end @@ -247,7 +247,7 @@ defmodule Pleroma.HTMLTest do              "<a href=\"https://pleroma.gov/media/d24caa3a498e21e0298377a9ca0149a4f4f8b767178aacf837542282e2d94fb1.png?name=image.png\" class=\"attachment\">image.png</a>"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert {:ok, nil} = HTML.extract_first_external_url_from_object(object)      end diff --git a/test/pleroma/http/adapter_helper/gun_test.exs b/test/pleroma/http/adapter_helper/gun_test.exs index 80589c73d..cfb68557d 100644 --- a/test/pleroma/http/adapter_helper/gun_test.exs +++ b/test/pleroma/http/adapter_helper/gun_test.exs @@ -1,14 +1,13 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTTP.AdapterHelper.GunTest do -  use ExUnit.Case, async: true +  use ExUnit.Case    use Pleroma.Tests.Helpers    import Mox -  alias Pleroma.Config    alias Pleroma.HTTP.AdapterHelper.Gun    setup :verify_on_exit! @@ -52,9 +51,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do      end      test "parses string proxy host & port" do -      proxy = Config.get([:http, :proxy_url]) -      Config.put([:http, :proxy_url], "localhost:8123") -      on_exit(fn -> Config.put([:http, :proxy_url], proxy) end) +      clear_config([:http, :proxy_url], "localhost:8123")        uri = URI.parse("https://some-domain.com")        opts = Gun.options([receive_conn: false], uri) @@ -62,9 +59,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do      end      test "parses tuple proxy scheme host and port" do -      proxy = Config.get([:http, :proxy_url]) -      Config.put([:http, :proxy_url], {:socks, 'localhost', 1234}) -      on_exit(fn -> Config.put([:http, :proxy_url], proxy) end) +      clear_config([:http, :proxy_url], {:socks, 'localhost', 1234})        uri = URI.parse("https://some-domain.com")        opts = Gun.options([receive_conn: false], uri) @@ -72,9 +67,7 @@ defmodule Pleroma.HTTP.AdapterHelper.GunTest do      end      test "passed opts have more weight than defaults" do -      proxy = Config.get([:http, :proxy_url]) -      Config.put([:http, :proxy_url], {:socks5, 'localhost', 1234}) -      on_exit(fn -> Config.put([:http, :proxy_url], proxy) end) +      clear_config([:http, :proxy_url], {:socks5, 'localhost', 1234})        uri = URI.parse("https://some-domain.com")        opts = Gun.options([receive_conn: false, proxy: {'example.com', 4321}], uri) diff --git a/test/pleroma/http/adapter_helper/hackney_test.exs b/test/pleroma/http/adapter_helper/hackney_test.exs index f2361ff0b..85150a65c 100644 --- a/test/pleroma/http/adapter_helper/hackney_test.exs +++ b/test/pleroma/http/adapter_helper/hackney_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTTP.AdapterHelper.HackneyTest do diff --git a/test/pleroma/http/adapter_helper_test.exs b/test/pleroma/http/adapter_helper_test.exs index 24d501ad5..3c8c89164 100644 --- a/test/pleroma/http/adapter_helper_test.exs +++ b/test/pleroma/http/adapter_helper_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTTP.AdapterHelperTest do diff --git a/test/pleroma/http/ex_aws_test.exs b/test/pleroma/http/ex_aws_test.exs index d0b00ca26..4cbc440bd 100644 --- a/test/pleroma/http/ex_aws_test.exs +++ b/test/pleroma/http/ex_aws_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTTP.ExAwsTest do diff --git a/test/pleroma/http/request_builder_test.exs b/test/pleroma/http/request_builder_test.exs index fab909905..e9b0c4a8a 100644 --- a/test/pleroma/http/request_builder_test.exs +++ b/test/pleroma/http/request_builder_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTTP.RequestBuilderTest do diff --git a/test/pleroma/http/tzdata_test.exs b/test/pleroma/http/tzdata_test.exs index 3e605d33b..1161bfaef 100644 --- a/test/pleroma/http/tzdata_test.exs +++ b/test/pleroma/http/tzdata_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTTP.TzdataTest do diff --git a/test/pleroma/http_test.exs b/test/pleroma/http_test.exs index d394bb942..e6a6d31b3 100644 --- a/test/pleroma/http_test.exs +++ b/test/pleroma/http_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.HTTPTest do diff --git a/test/pleroma/instances/instance_test.exs b/test/pleroma/instances/instance_test.exs index 2c6389e4f..bacc0b19b 100644 --- a/test/pleroma/instances/instance_test.exs +++ b/test/pleroma/instances/instance_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Instances.InstanceTest do diff --git a/test/pleroma/instances_test.exs b/test/pleroma/instances_test.exs index 5d0ce6237..03f9e4e97 100644 --- a/test/pleroma/instances_test.exs +++ b/test/pleroma/instances_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.InstancesTest do diff --git a/test/pleroma/integration/federation_test.exs b/test/pleroma/integration/federation_test.exs index 10d71fb88..da433e2c0 100644 --- a/test/pleroma/integration/federation_test.exs +++ b/test/pleroma/integration/federation_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Integration.FederationTest do diff --git a/test/pleroma/integration/mastodon_websocket_test.exs b/test/pleroma/integration/mastodon_websocket_test.exs index bb8e795b7..43ec57893 100644 --- a/test/pleroma/integration/mastodon_websocket_test.exs +++ b/test/pleroma/integration/mastodon_websocket_test.exs @@ -1,8 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Integration.MastodonWebsocketTest do +  # Needs a streamer, needs to stay synchronous    use Pleroma.DataCase    import ExUnit.CaptureLog diff --git a/test/pleroma/job_queue_monitor_test.exs b/test/pleroma/job_queue_monitor_test.exs index 65c1e9f29..eebf602c5 100644 --- a/test/pleroma/job_queue_monitor_test.exs +++ b/test/pleroma/job_queue_monitor_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.JobQueueMonitorTest do diff --git a/test/pleroma/keys_test.exs b/test/pleroma/keys_test.exs index 9e8528cba..9a15bf06e 100644 --- a/test/pleroma/keys_test.exs +++ b/test/pleroma/keys_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.KeysTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Keys diff --git a/test/pleroma/list_test.exs b/test/pleroma/list_test.exs index b5572cbae..7e66ad385 100644 --- a/test/pleroma/list_test.exs +++ b/test/pleroma/list_test.exs @@ -1,10 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ListTest do    alias Pleroma.Repo -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/marker_test.exs b/test/pleroma/marker_test.exs index 7b3943c7b..5f87a1c38 100644 --- a/test/pleroma/marker_test.exs +++ b/test/pleroma/marker_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.MarkerTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Marker    import Pleroma.Factory diff --git a/test/pleroma/mfa/backup_codes_test.exs b/test/pleroma/mfa/backup_codes_test.exs index 41adb1e96..59f984e32 100644 --- a/test/pleroma/mfa/backup_codes_test.exs +++ b/test/pleroma/mfa/backup_codes_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.MFA.BackupCodesTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.MFA.BackupCodes diff --git a/test/pleroma/mfa/totp_test.exs b/test/pleroma/mfa/totp_test.exs index 9edb6fd54..828993866 100644 --- a/test/pleroma/mfa/totp_test.exs +++ b/test/pleroma/mfa/totp_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.MFA.TOTPTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.MFA.TOTP diff --git a/test/pleroma/mfa_test.exs b/test/pleroma/mfa_test.exs index 8875cefd9..76ba1a99d 100644 --- a/test/pleroma/mfa_test.exs +++ b/test/pleroma/mfa_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.MFATest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.MFA @@ -30,8 +30,8 @@ defmodule Pleroma.MFATest do        {:ok, [code1, code2]} = MFA.generate_backup_codes(user)        updated_user = refresh_record(user)        [hash1, hash2] = updated_user.multi_factor_authentication_settings.backup_codes -      assert Pbkdf2.verify_pass(code1, hash1) -      assert Pbkdf2.verify_pass(code2, hash2) +      assert Pleroma.Password.Pbkdf2.verify_pass(code1, hash1) +      assert Pleroma.Password.Pbkdf2.verify_pass(code2, hash2)      end    end diff --git a/test/pleroma/migration_helper/notification_backfill_test.exs b/test/pleroma/migration_helper/notification_backfill_test.exs index 2a62a2b00..fd253b530 100644 --- a/test/pleroma/migration_helper/notification_backfill_test.exs +++ b/test/pleroma/migration_helper/notification_backfill_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.MigrationHelper.NotificationBackfillTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.MigrationHelper.NotificationBackfill diff --git a/test/pleroma/moderation_log_test.exs b/test/pleroma/moderation_log_test.exs index 03b32a060..c6c170c45 100644 --- a/test/pleroma/moderation_log_test.exs +++ b/test/pleroma/moderation_log_test.exs @@ -1,12 +1,12 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ModerationLogTest do    alias Pleroma.Activity    alias Pleroma.ModerationLog -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/notification_test.exs b/test/pleroma/notification_test.exs index a6558f995..abf1b0410 100644 --- a/test/pleroma/notification_test.exs +++ b/test/pleroma/notification_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.NotificationTest do @@ -45,6 +45,20 @@ defmodule Pleroma.NotificationTest do        assert notification.type == "pleroma:report"      end +    test "suppresses notification to reporter if reporter is an admin" do +      reporting_admin = insert(:user, is_admin: true) +      reported_user = insert(:user) +      other_admin = insert(:user, is_admin: true) + +      {:ok, activity} = CommonAPI.report(reporting_admin, %{account_id: reported_user.id}) + +      {:ok, [notification]} = Notification.create_notifications(activity) + +      refute notification.user_id == reporting_admin.id +      assert notification.user_id == other_admin.id +      assert notification.type == "pleroma:report" +    end +      test "creates a notification for an emoji reaction" do        user = insert(:user)        other_user = insert(:user) @@ -976,7 +990,6 @@ defmodule Pleroma.NotificationTest do        assert Enum.empty?(Notification.for_user(local_user))      end -    @tag capture_log: true      test "move activity generates a notification" do        %{ap_id: old_ap_id} = old_user = insert(:user)        %{ap_id: new_ap_id} = new_user = insert(:user, also_known_as: [old_ap_id]) @@ -986,18 +999,6 @@ defmodule Pleroma.NotificationTest do        User.follow(follower, old_user)        User.follow(other_follower, old_user) -      old_user_url = old_user.ap_id - -      body = -        File.read!("test/fixtures/users_mock/localhost.json") -        |> String.replace("{{nickname}}", old_user.nickname) -        |> Jason.encode!() - -      Tesla.Mock.mock(fn -        %{method: :get, url: ^old_user_url} -> -          %Tesla.Env{status: 200, body: body} -      end) -        Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)        ObanHelpers.perform_all() diff --git a/test/pleroma/object/containment_test.exs b/test/pleroma/object/containment_test.exs index 90b6dccf2..fb2fb7d49 100644 --- a/test/pleroma/object/containment_test.exs +++ b/test/pleroma/object/containment_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Object.ContainmentTest do diff --git a/test/pleroma/object/fetcher_test.exs b/test/pleroma/object/fetcher_test.exs index 7df6af7fe..a7ac90348 100644 --- a/test/pleroma/object/fetcher_test.exs +++ b/test/pleroma/object/fetcher_test.exs @@ -1,12 +1,11 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Object.FetcherTest do    use Pleroma.DataCase    alias Pleroma.Activity -  alias Pleroma.Config    alias Pleroma.Object    alias Pleroma.Object.Fetcher @@ -87,20 +86,20 @@ defmodule Pleroma.Object.FetcherTest do      setup do: clear_config([:instance, :federation_incoming_replies_max_depth])      test "it returns thread depth exceeded error if thread depth is exceeded" do -      Config.put([:instance, :federation_incoming_replies_max_depth], 0) +      clear_config([:instance, :federation_incoming_replies_max_depth], 0)        assert {:error, "Max thread distance exceeded."} =                 Fetcher.fetch_object_from_id(@ap_id, depth: 1)      end      test "it fetches object if max thread depth is restricted to 0 and depth is not specified" do -      Config.put([:instance, :federation_incoming_replies_max_depth], 0) +      clear_config([:instance, :federation_incoming_replies_max_depth], 0)        assert {:ok, _} = Fetcher.fetch_object_from_id(@ap_id)      end      test "it fetches object if requested depth does not exceed max thread depth" do -      Config.put([:instance, :federation_incoming_replies_max_depth], 10) +      clear_config([:instance, :federation_incoming_replies_max_depth], 10)        assert {:ok, _} = Fetcher.fetch_object_from_id(@ap_id, depth: 10)      end @@ -245,7 +244,7 @@ defmodule Pleroma.Object.FetcherTest do                     Pleroma.Signature,                     [:passthrough],                     [] do -      Config.put([:activitypub, :sign_object_fetches], true) +      clear_config([:activitypub, :sign_object_fetches], true)        Fetcher.fetch_object_from_id("http://mastodon.example.org/@admin/99541947525187367") @@ -256,7 +255,7 @@ defmodule Pleroma.Object.FetcherTest do                     Pleroma.Signature,                     [:passthrough],                     [] do -      Config.put([:activitypub, :sign_object_fetches], false) +      clear_config([:activitypub, :sign_object_fetches], false)        Fetcher.fetch_object_from_id("http://mastodon.example.org/@admin/99541947525187367") diff --git a/test/pleroma/object_test.exs b/test/pleroma/object_test.exs index 5d4e6fb84..8320660a5 100644 --- a/test/pleroma/object_test.exs +++ b/test/pleroma/object_test.exs @@ -1,14 +1,17 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ObjectTest do    use Pleroma.DataCase    use Oban.Testing, repo: Pleroma.Repo +    import ExUnit.CaptureLog    import Pleroma.Factory    import Tesla.Mock +    alias Pleroma.Activity +  alias Pleroma.Hashtag    alias Pleroma.Object    alias Pleroma.Repo    alias Pleroma.Tests.ObanHelpers @@ -78,8 +81,8 @@ defmodule Pleroma.ObjectTest do      setup do: clear_config([:instance, :cleanup_attachments])      test "Disabled via config" do -      Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) -      Pleroma.Config.put([:instance, :cleanup_attachments], false) +      clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +      clear_config([:instance, :cleanup_attachments], false)        file = %Plug.Upload{          content_type: "image/jpeg", @@ -112,8 +115,8 @@ defmodule Pleroma.ObjectTest do      end      test "in subdirectories" do -      Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) -      Pleroma.Config.put([:instance, :cleanup_attachments], true) +      clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +      clear_config([:instance, :cleanup_attachments], true)        file = %Plug.Upload{          content_type: "image/jpeg", @@ -146,9 +149,9 @@ defmodule Pleroma.ObjectTest do      end      test "with dedupe enabled" do -      Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) -      Pleroma.Config.put([Pleroma.Upload, :filters], [Pleroma.Upload.Filter.Dedupe]) -      Pleroma.Config.put([:instance, :cleanup_attachments], true) +      clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +      clear_config([Pleroma.Upload, :filters], [Pleroma.Upload.Filter.Dedupe]) +      clear_config([:instance, :cleanup_attachments], true)        uploads_dir = Pleroma.Config.get!([Pleroma.Uploaders.Local, :uploads]) @@ -184,8 +187,8 @@ defmodule Pleroma.ObjectTest do      end      test "with objects that have legacy data.url attribute" do -      Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) -      Pleroma.Config.put([:instance, :cleanup_attachments], true) +      clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +      clear_config([:instance, :cleanup_attachments], true)        file = %Plug.Upload{          content_type: "image/jpeg", @@ -220,9 +223,9 @@ defmodule Pleroma.ObjectTest do      end      test "With custom base_url" do -      Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) -      Pleroma.Config.put([Pleroma.Upload, :base_url], "https://sub.domain.tld/dir/") -      Pleroma.Config.put([:instance, :cleanup_attachments], true) +      clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +      clear_config([Pleroma.Upload, :base_url], "https://sub.domain.tld/dir/") +      clear_config([:instance, :cleanup_attachments], true)        file = %Plug.Upload{          content_type: "image/jpeg", @@ -256,23 +259,22 @@ defmodule Pleroma.ObjectTest do    end    describe "normalizer" do -    test "fetches unknown objects by default" do -      %Object{} = -        object = Object.normalize("http://mastodon.example.org/@admin/99541947525187367") - -      assert object.data["url"] == "http://mastodon.example.org/@admin/99541947525187367" +    @url "http://mastodon.example.org/@admin/99541947525187367" +    test "does not fetch unknown objects by default" do +      assert nil == Object.normalize(@url)      end -    test "fetches unknown objects when fetch_remote is explicitly true" do -      %Object{} = -        object = Object.normalize("http://mastodon.example.org/@admin/99541947525187367", true) +    test "fetches unknown objects when fetch is explicitly true" do +      %Object{} = object = Object.normalize(@url, fetch: true) -      assert object.data["url"] == "http://mastodon.example.org/@admin/99541947525187367" +      assert object.data["url"] == @url      end -    test "does not fetch unknown objects when fetch_remote is false" do +    test "does not fetch unknown objects when fetch is false" do        assert is_nil( -               Object.normalize("http://mastodon.example.org/@admin/99541947525187367", false) +               Object.normalize(@url, +                 fetch: false +               )               )      end    end @@ -310,7 +312,10 @@ defmodule Pleroma.ObjectTest do        mock_modified: mock_modified      } do        %Object{} = -        object = Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d") +        object = +        Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d", +          fetch: true +        )        Object.set_cache(object) @@ -332,7 +337,10 @@ defmodule Pleroma.ObjectTest do      test "returns the old object if refetch fails", %{mock_modified: mock_modified} do        %Object{} = -        object = Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d") +        object = +        Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d", +          fetch: true +        )        Object.set_cache(object) @@ -355,7 +363,10 @@ defmodule Pleroma.ObjectTest do        mock_modified: mock_modified      } do        %Object{} = -        object = Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d") +        object = +        Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d", +          fetch: true +        )        Object.set_cache(object) @@ -377,7 +388,10 @@ defmodule Pleroma.ObjectTest do      test "preserves internal fields on refetch", %{mock_modified: mock_modified} do        %Object{} = -        object = Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d") +        object = +        Object.normalize("https://patch.cx/objects/9a172665-2bc5-452d-8428-2361d4c33b1d", +          fetch: true +        )        Object.set_cache(object) @@ -406,4 +420,28 @@ defmodule Pleroma.ObjectTest do        assert updated_object.data["like_count"] == 1      end    end + +  describe ":hashtags association" do +    test "Hashtag records are created with Object record and updated on its change" do +      user = insert(:user) + +      {:ok, %{object: object}} = +        CommonAPI.post(user, %{status: "some text #hashtag1 #hashtag2 ..."}) + +      assert [%Hashtag{name: "hashtag1"}, %Hashtag{name: "hashtag2"}] = +               Enum.sort_by(object.hashtags, & &1.name) + +      {:ok, object} = Object.update_data(object, %{"tag" => []}) + +      assert [] = object.hashtags + +      object = Object.get_by_id(object.id) |> Repo.preload(:hashtags) +      assert [] = object.hashtags + +      {:ok, object} = Object.update_data(object, %{"tag" => ["abc", "def"]}) + +      assert [%Hashtag{name: "abc"}, %Hashtag{name: "def"}] = +               Enum.sort_by(object.hashtags, & &1.name) +    end +  end  end diff --git a/test/pleroma/otp_version_test.exs b/test/pleroma/otp_version_test.exs index 7d2538ec8..736d440af 100644 --- a/test/pleroma/otp_version_test.exs +++ b/test/pleroma/otp_version_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.OTPVersionTest do diff --git a/test/pleroma/pagination_test.exs b/test/pleroma/pagination_test.exs index e526f23e8..bc26c8b46 100644 --- a/test/pleroma/pagination_test.exs +++ b/test/pleroma/pagination_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.PaginationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/password/pbkdf2_test.exs b/test/pleroma/password/pbkdf2_test.exs new file mode 100644 index 000000000..e55348f9a --- /dev/null +++ b/test/pleroma/password/pbkdf2_test.exs @@ -0,0 +1,35 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Password.Pbkdf2Test do +  use Pleroma.DataCase, async: true + +  alias Pleroma.Password.Pbkdf2, as: Password + +  test "it generates the same hash as pbkd2_elixir" do +    # hash = Pbkdf2.hash_pwd_salt("password") +    hash = +      "$pbkdf2-sha512$1$QJpEYw8iBKcnY.4Rm0eCVw$UBPeWQ91RxSv3snxsb/ZzMeG/2aa03c541bbo8vQudREGNta5t8jBQrd00fyJp8RjaqfvgdZxy2rhSwljyu21g" + +    # Use the same randomly generated salt +    salt = Password.decode64("QJpEYw8iBKcnY.4Rm0eCVw") + +    assert hash == Password.hash_pwd_salt("password", salt: salt) +  end + +  @tag skip: "Works when Pbkd2 is present. Source: trust me bro" +  test "Pbkdf2 can verify passwords generated with it" do +    # Commented to prevent warnings. +    # hash = Password.hash_pwd_salt("password") +    # assert Pbkdf2.verify_pass("password", hash) +  end + +  test "it verifies pbkdf2_elixir hashes" do +    # hash = Pbkdf2.hash_pwd_salt("password") +    hash = +      "$pbkdf2-sha512$1$QJpEYw8iBKcnY.4Rm0eCVw$UBPeWQ91RxSv3snxsb/ZzMeG/2aa03c541bbo8vQudREGNta5t8jBQrd00fyJp8RjaqfvgdZxy2rhSwljyu21g" + +    assert Password.verify_pass("password", hash) +  end +end diff --git a/test/pleroma/registration_test.exs b/test/pleroma/registration_test.exs index 7db8e3664..6e4ad9487 100644 --- a/test/pleroma/registration_test.exs +++ b/test/pleroma/registration_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.RegistrationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/repo/migrations/autolinker_to_linkify_test.exs b/test/pleroma/repo/migrations/autolinker_to_linkify_test.exs index 84f520fe4..a7d4d493c 100644 --- a/test/pleroma/repo/migrations/autolinker_to_linkify_test.exs +++ b/test/pleroma/repo/migrations/autolinker_to_linkify_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Repo.Migrations.AutolinkerToLinkifyTest do @@ -37,7 +37,7 @@ defmodule Pleroma.Repo.Migrations.AutolinkerToLinkifyTest do               strip_prefix: false             ] -    Pleroma.Config.put(Pleroma.Formatter, new_opts) +    clear_config(Pleroma.Formatter, new_opts)      assert new_opts == Pleroma.Config.get(Pleroma.Formatter)      {text, _mentions, []} = diff --git a/test/pleroma/repo/migrations/confirm_logged_in_users_test.exs b/test/pleroma/repo/migrations/confirm_logged_in_users_test.exs new file mode 100644 index 000000000..99d17f62a --- /dev/null +++ b/test/pleroma/repo/migrations/confirm_logged_in_users_test.exs @@ -0,0 +1,40 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Repo.Migrations.ConfirmLoggedInUsersTest do +  alias Pleroma.Repo +  alias Pleroma.User +  use Pleroma.DataCase, async: true +  import Ecto.Query +  import Pleroma.Factory +  import Pleroma.Tests.Helpers + +  setup_all do: require_migration("20201231185546_confirm_logged_in_users") + +  test "up/0 confirms unconfirmed but previously-logged-in users", %{migration: migration} do +    insert_list(25, :oauth_token) +    Repo.update_all(User, set: [is_confirmed: false]) +    insert_list(5, :user, is_confirmed: false) + +    count = +      User +      |> where(is_confirmed: false) +      |> Repo.aggregate(:count) + +    assert count == 30 + +    assert {25, nil} == migration.up() + +    count = +      User +      |> where(is_confirmed: false) +      |> Repo.aggregate(:count) + +    assert count == 5 +  end + +  test "down/0 does nothing", %{migration: migration} do +    assert :noop == migration.down() +  end +end diff --git a/test/pleroma/repo/migrations/deprecate_public_endpoint_test.exs b/test/pleroma/repo/migrations/deprecate_public_endpoint_test.exs new file mode 100644 index 000000000..2ffc1b145 --- /dev/null +++ b/test/pleroma/repo/migrations/deprecate_public_endpoint_test.exs @@ -0,0 +1,60 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Repo.Migrations.DeprecatePublicEndpointTest do +  use Pleroma.DataCase +  import Pleroma.Factory +  import Pleroma.Tests.Helpers +  alias Pleroma.ConfigDB + +  setup do: clear_config(Pleroma.Upload) +  setup do: clear_config(Pleroma.Uploaders.S3) +  setup_all do: require_migration("20210113225652_deprecate_public_endpoint") + +  test "up/0 migrates public_endpoint to base_url", %{migration: migration} do +    s3_values = [ +      public_endpoint: "https://coolhost.com/", +      bucket: "secret_bucket" +    ] + +    insert(:config, group: :pleroma, key: Pleroma.Uploaders.S3, value: s3_values) + +    upload_values = [ +      uploader: Pleroma.Uploaders.S3 +    ] + +    insert(:config, group: :pleroma, key: Pleroma.Upload, value: upload_values) + +    migration.up() + +    assert [bucket: "secret_bucket"] == +             ConfigDB.get_by_params(%{group: :pleroma, key: Pleroma.Uploaders.S3}).value + +    assert [uploader: Pleroma.Uploaders.S3, base_url: "https://coolhost.com/"] == +             ConfigDB.get_by_params(%{group: :pleroma, key: Pleroma.Upload}).value +  end + +  test "down/0 reverts base_url to public_endpoint", %{migration: migration} do +    s3_values = [ +      bucket: "secret_bucket" +    ] + +    insert(:config, group: :pleroma, key: Pleroma.Uploaders.S3, value: s3_values) + +    upload_values = [ +      uploader: Pleroma.Uploaders.S3, +      base_url: "https://coolhost.com/" +    ] + +    insert(:config, group: :pleroma, key: Pleroma.Upload, value: upload_values) + +    migration.down() + +    assert [bucket: "secret_bucket", public_endpoint: "https://coolhost.com/"] == +             ConfigDB.get_by_params(%{group: :pleroma, key: Pleroma.Uploaders.S3}).value + +    assert [uploader: Pleroma.Uploaders.S3] == +             ConfigDB.get_by_params(%{group: :pleroma, key: Pleroma.Upload}).value +  end +end diff --git a/test/pleroma/repo/migrations/fix_legacy_tags_test.exs b/test/pleroma/repo/migrations/fix_legacy_tags_test.exs index 432055e45..0a1d1d0bb 100644 --- a/test/pleroma/repo/migrations/fix_legacy_tags_test.exs +++ b/test/pleroma/repo/migrations/fix_legacy_tags_test.exs @@ -1,10 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Repo.Migrations.FixLegacyTagsTest do    alias Pleroma.User -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    import Pleroma.Tests.Helpers diff --git a/test/pleroma/repo/migrations/fix_malformed_formatter_config_test.exs b/test/pleroma/repo/migrations/fix_malformed_formatter_config_test.exs index 61528599a..65c9961b0 100644 --- a/test/pleroma/repo/migrations/fix_malformed_formatter_config_test.exs +++ b/test/pleroma/repo/migrations/fix_malformed_formatter_config_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Repo.Migrations.FixMalformedFormatterConfigTest do @@ -34,7 +34,7 @@ defmodule Pleroma.Repo.Migrations.FixMalformedFormatterConfigTest do               strip_prefix: false             ] -    Pleroma.Config.put(Pleroma.Formatter, new_opts) +    clear_config(Pleroma.Formatter, new_opts)      assert new_opts == Pleroma.Config.get(Pleroma.Formatter)      {text, _mentions, []} = diff --git a/test/pleroma/repo/migrations/move_welcome_settings_test.exs b/test/pleroma/repo/migrations/move_welcome_settings_test.exs index 53d05a55a..1da6b8a04 100644 --- a/test/pleroma/repo/migrations/move_welcome_settings_test.exs +++ b/test/pleroma/repo/migrations/move_welcome_settings_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Repo.Migrations.MoveWelcomeSettingsTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    import Pleroma.Tests.Helpers    alias Pleroma.ConfigDB diff --git a/test/pleroma/repo_test.exs b/test/pleroma/repo_test.exs index 155791be2..9e14bdbd1 100644 --- a/test/pleroma/repo_test.exs +++ b/test/pleroma/repo_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.RepoTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.User diff --git a/test/pleroma/report_note_test.exs b/test/pleroma/report_note_test.exs index 25c1d6a61..2620560a0 100644 --- a/test/pleroma/report_note_test.exs +++ b/test/pleroma/report_note_test.exs @@ -1,10 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ReportNoteTest do    alias Pleroma.ReportNote -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    test "create/3" do diff --git a/test/pleroma/reverse_proxy_test.exs b/test/pleroma/reverse_proxy_test.exs index 8df63de65..a4dd8e99a 100644 --- a/test/pleroma/reverse_proxy_test.exs +++ b/test/pleroma/reverse_proxy_test.exs @@ -1,10 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ReverseProxyTest do -  use Pleroma.Web.ConnCase, async: true - +  use Pleroma.Web.ConnCase    import ExUnit.CaptureLog    import Mox @@ -19,24 +18,23 @@ defmodule Pleroma.ReverseProxyTest do    setup :verify_on_exit! -  defp user_agent_mock(user_agent, invokes) do -    json = Jason.encode!(%{"user-agent": user_agent}) - +  defp request_mock(invokes) do      ClientMock -    |> expect(:request, fn :get, url, _, _, _ -> +    |> expect(:request, fn :get, url, headers, _body, _opts ->        Registry.register(ClientMock, url, 0) +      body = headers |> Enum.into(%{}) |> Jason.encode!()        {:ok, 200,         [           {"content-type", "application/json"}, -         {"content-length", byte_size(json) |> to_string()} -       ], %{url: url}} +         {"content-length", byte_size(body) |> to_string()} +       ], %{url: url, body: body}}      end) -    |> expect(:stream_body, invokes, fn %{url: url} = client -> +    |> expect(:stream_body, invokes, fn %{url: url, body: body} = client ->        case Registry.lookup(ClientMock, url) do          [{_, 0}] ->            Registry.update_value(ClientMock, url, &(&1 + 1)) -          {:ok, json, client} +          {:ok, body, client}          [{_, 1}] ->            Registry.unregister(ClientMock, url) @@ -47,7 +45,7 @@ defmodule Pleroma.ReverseProxyTest do    describe "reverse proxy" do      test "do not track successful request", %{conn: conn} do -      user_agent_mock("hackney/1.15.1", 2) +      request_mock(2)        url = "/success"        conn = ReverseProxy.call(conn, url) @@ -57,18 +55,15 @@ defmodule Pleroma.ReverseProxyTest do      end    end -  describe "user-agent" do -    test "don't keep", %{conn: conn} do -      user_agent_mock("hackney/1.15.1", 2) -      conn = ReverseProxy.call(conn, "/user-agent") -      assert json_response(conn, 200) == %{"user-agent" => "hackney/1.15.1"} -    end +  test "use Pleroma's user agent in the request; don't pass the client's", %{conn: conn} do +    request_mock(2) -    test "keep", %{conn: conn} do -      user_agent_mock(Pleroma.Application.user_agent(), 2) -      conn = ReverseProxy.call(conn, "/user-agent-keep", keep_user_agent: true) -      assert json_response(conn, 200) == %{"user-agent" => Pleroma.Application.user_agent()} -    end +    conn = +      conn +      |> Plug.Conn.put_req_header("user-agent", "fake/1.0") +      |> ReverseProxy.call("/user-agent") + +    assert json_response(conn, 200) == %{"user-agent" => Pleroma.Application.user_agent()}    end    test "closed connection", %{conn: conn} do @@ -115,7 +110,7 @@ defmodule Pleroma.ReverseProxyTest do    describe "max_body" do      test "length returns error if content-length more than option", %{conn: conn} do -      user_agent_mock("hackney/1.15.1", 0) +      request_mock(0)        assert capture_log(fn ->                 ReverseProxy.call(conn, "/huge-file", max_body_length: 4) diff --git a/test/pleroma/runtime_test.exs b/test/pleroma/runtime_test.exs index 010594fcd..b9e769602 100644 --- a/test/pleroma/runtime_test.exs +++ b/test/pleroma/runtime_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.RuntimeTest do diff --git a/test/pleroma/safe_jsonb_set_test.exs b/test/pleroma/safe_jsonb_set_test.exs index 8b1274545..69d696c1b 100644 --- a/test/pleroma/safe_jsonb_set_test.exs +++ b/test/pleroma/safe_jsonb_set_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.SafeJsonbSetTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    test "it doesn't wipe the object when asked to set the value to NULL" do      assert %{rows: [[%{"key" => "value", "test" => nil}]]} = diff --git a/test/pleroma/scheduled_activity_test.exs b/test/pleroma/scheduled_activity_test.exs index 7faa5660d..ef91e9bce 100644 --- a/test/pleroma/scheduled_activity_test.exs +++ b/test/pleroma/scheduled_activity_test.exs @@ -1,22 +1,21 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.ScheduledActivityTest do    use Pleroma.DataCase -  alias Pleroma.DataCase +    alias Pleroma.ScheduledActivity +    import Pleroma.Factory    setup do: clear_config([ScheduledActivity, :enabled]) -  setup context do -    DataCase.ensure_local_uploader(context) -  end +  setup [:ensure_local_uploader]    describe "creation" do      test "scheduled activities with jobs when ScheduledActivity enabled" do -      Pleroma.Config.put([ScheduledActivity, :enabled], true) +      clear_config([ScheduledActivity, :enabled], true)        user = insert(:user)        today = @@ -35,7 +34,7 @@ defmodule Pleroma.ScheduledActivityTest do      end      test "scheduled activities without jobs when ScheduledActivity disabled" do -      Pleroma.Config.put([ScheduledActivity, :enabled], false) +      clear_config([ScheduledActivity, :enabled], false)        user = insert(:user)        today = diff --git a/test/pleroma/signature_test.exs b/test/pleroma/signature_test.exs index a7a75aa4d..047c537e0 100644 --- a/test/pleroma/signature_test.exs +++ b/test/pleroma/signature_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.SignatureTest do diff --git a/test/pleroma/stats_test.exs b/test/pleroma/stats_test.exs index 74bf785b0..fd3195969 100644 --- a/test/pleroma/stats_test.exs +++ b/test/pleroma/stats_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.StatsTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/upload/filter/anonymize_filename_test.exs b/test/pleroma/upload/filter/anonymize_filename_test.exs index 7ef01ce91..9387c1abc 100644 --- a/test/pleroma/upload/filter/anonymize_filename_test.exs +++ b/test/pleroma/upload/filter/anonymize_filename_test.exs @@ -1,11 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Upload.Filter.AnonymizeFilenameTest do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.Upload    setup do @@ -23,13 +22,13 @@ defmodule Pleroma.Upload.Filter.AnonymizeFilenameTest do    setup do: clear_config([Pleroma.Upload.Filter.AnonymizeFilename, :text])    test "it replaces filename on pre-defined text", %{upload_file: upload_file} do -    Config.put([Upload.Filter.AnonymizeFilename, :text], "custom-file.png") +    clear_config([Upload.Filter.AnonymizeFilename, :text], "custom-file.png")      {:ok, :filtered, %Upload{name: name}} = Upload.Filter.AnonymizeFilename.filter(upload_file)      assert name == "custom-file.png"    end    test "it replaces filename on pre-defined text expression", %{upload_file: upload_file} do -    Config.put([Upload.Filter.AnonymizeFilename, :text], "custom-file.{extension}") +    clear_config([Upload.Filter.AnonymizeFilename, :text], "custom-file.{extension}")      {:ok, :filtered, %Upload{name: name}} = Upload.Filter.AnonymizeFilename.filter(upload_file)      assert name == "custom-file.jpg"    end diff --git a/test/pleroma/upload/filter/dedupe_test.exs b/test/pleroma/upload/filter/dedupe_test.exs index 92a3d7df3..f00ba12f9 100644 --- a/test/pleroma/upload/filter/dedupe_test.exs +++ b/test/pleroma/upload/filter/dedupe_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Upload.Filter.DedupeTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Upload    alias Pleroma.Upload.Filter.Dedupe diff --git a/test/pleroma/upload/filter/exiftool_test.exs b/test/pleroma/upload/filter/exiftool_test.exs index 6b978b64c..cfbe34be8 100644 --- a/test/pleroma/upload/filter/exiftool_test.exs +++ b/test/pleroma/upload/filter/exiftool_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Upload.Filter.ExiftoolTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Upload.Filter    test "apply exiftool filter" do diff --git a/test/pleroma/upload/filter/mogrifun_test.exs b/test/pleroma/upload/filter/mogrifun_test.exs index fc2f68276..d2b183e90 100644 --- a/test/pleroma/upload/filter/mogrifun_test.exs +++ b/test/pleroma/upload/filter/mogrifun_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Upload.Filter.MogrifunTest do diff --git a/test/pleroma/upload/filter/mogrify_test.exs b/test/pleroma/upload/filter/mogrify_test.exs index 6dee02e8b..d62cd83b4 100644 --- a/test/pleroma/upload/filter/mogrify_test.exs +++ b/test/pleroma/upload/filter/mogrify_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Upload.Filter.MogrifyTest do diff --git a/test/pleroma/upload/filter_test.exs b/test/pleroma/upload/filter_test.exs index 09394929c..f0053ed9b 100644 --- a/test/pleroma/upload/filter_test.exs +++ b/test/pleroma/upload/filter_test.exs @@ -1,17 +1,16 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Upload.FilterTest do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.Upload.Filter    setup do: clear_config([Pleroma.Upload.Filter.AnonymizeFilename, :text])    test "applies filters" do -    Config.put([Pleroma.Upload.Filter.AnonymizeFilename, :text], "custom-file.png") +    clear_config([Pleroma.Upload.Filter.AnonymizeFilename, :text], "custom-file.png")      File.cp!(        "test/fixtures/image.jpg", diff --git a/test/pleroma/upload_test.exs b/test/pleroma/upload_test.exs index f52d4dff6..f1ab82a57 100644 --- a/test/pleroma/upload_test.exs +++ b/test/pleroma/upload_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.UploadTest do @@ -133,7 +133,7 @@ defmodule Pleroma.UploadTest do        assert %{"url" => [%{"href" => url}]} = data -      assert String.starts_with?(url, Pleroma.Web.base_url() <> "/media/") +      assert String.starts_with?(url, Pleroma.Upload.base_url())      end      test "copies the file to the configured folder with deduping" do @@ -148,8 +148,8 @@ defmodule Pleroma.UploadTest do        {:ok, data} = Upload.store(file, filters: [Pleroma.Upload.Filter.Dedupe])        assert List.first(data["url"])["href"] == -               Pleroma.Web.base_url() <> -                 "/media/e30397b58d226d6583ab5b8b3c5defb0c682bda5c31ef07a9f57c1c4986e3781.jpg" +               Pleroma.Upload.base_url() <> +                 "e30397b58d226d6583ab5b8b3c5defb0c682bda5c31ef07a9f57c1c4986e3781.jpg"      end      test "copies the file to the configured folder without deduping" do diff --git a/test/pleroma/uploaders/local_test.exs b/test/pleroma/uploaders/local_test.exs index 1ce7be485..0a5952f50 100644 --- a/test/pleroma/uploaders/local_test.exs +++ b/test/pleroma/uploaders/local_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Uploaders.LocalTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Uploaders.Local    describe "get_file/1" do diff --git a/test/pleroma/uploaders/s3_test.exs b/test/pleroma/uploaders/s3_test.exs index e7a013dd8..2711e2c8d 100644 --- a/test/pleroma/uploaders/s3_test.exs +++ b/test/pleroma/uploaders/s3_test.exs @@ -1,21 +1,21 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Uploaders.S3Test do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.Uploaders.S3    import Mock    import ExUnit.CaptureLog -  setup do: -          clear_config(Pleroma.Uploaders.S3, -            bucket: "test_bucket", -            public_endpoint: "https://s3.amazonaws.com" -          ) +  setup do +    clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.S3) +    clear_config([Pleroma.Upload, :base_url], "https://s3.amazonaws.com") +    clear_config([Pleroma.Uploaders.S3]) +    clear_config([Pleroma.Uploaders.S3, :bucket], "test_bucket") +  end    describe "get_file/1" do      test "it returns path to local folder for files" do @@ -26,12 +26,14 @@ defmodule Pleroma.Uploaders.S3Test do      end      test "it returns path without bucket when truncated_namespace set to ''" do -      Config.put([Pleroma.Uploaders.S3], +      clear_config([Pleroma.Uploaders.S3],          bucket: "test_bucket", -        public_endpoint: "https://s3.amazonaws.com", +        bucket_namespace: "myaccount",          truncated_namespace: ""        ) +      clear_config([Pleroma.Upload, :base_url], "https://s3.amazonaws.com") +        assert S3.get_file("test_image.jpg") == {                 :ok,                 {:url, "https://s3.amazonaws.com/test_image.jpg"} @@ -39,9 +41,8 @@ defmodule Pleroma.Uploaders.S3Test do      end      test "it returns path with bucket namespace when namespace is set" do -      Config.put([Pleroma.Uploaders.S3], +      clear_config([Pleroma.Uploaders.S3],          bucket: "test_bucket", -        public_endpoint: "https://s3.amazonaws.com",          bucket_namespace: "family"        ) diff --git a/test/pleroma/user/backup_test.exs b/test/pleroma/user/backup_test.exs index f68e4a029..b16152876 100644 --- a/test/pleroma/user/backup_test.exs +++ b/test/pleroma/user/backup_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.User.BackupTest do @@ -23,7 +23,7 @@ defmodule Pleroma.User.BackupTest do    end    test "it requries enabled email" do -    Pleroma.Config.put([Pleroma.Emails.Mailer, :enabled], false) +    clear_config([Pleroma.Emails.Mailer, :enabled], false)      user = insert(:user)      assert {:error, "Backups require enabled email"} == Backup.create(user)    end @@ -53,7 +53,7 @@ defmodule Pleroma.User.BackupTest do    end    test "it process a backup record" do -    Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +    clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local)      %{id: user_id} = user = insert(:user)      assert {:ok, %Oban.Job{args: %{"backup_id" => backup_id} = args}} = Backup.create(user) @@ -76,8 +76,8 @@ defmodule Pleroma.User.BackupTest do    end    test "it removes outdated backups after creating a fresh one" do -    Pleroma.Config.put([Backup, :limit_days], -1) -    Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +    clear_config([Backup, :limit_days], -1) +    clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local)      user = insert(:user)      assert {:ok, job1} = Backup.create(user) @@ -195,12 +195,8 @@ defmodule Pleroma.User.BackupTest do    describe "it uploads and deletes a backup archive" do      setup do -      clear_config(Pleroma.Uploaders.S3, -        bucket: "test_bucket", -        public_endpoint: "https://s3.amazonaws.com" -      ) - -      clear_config([Pleroma.Upload, :uploader]) +      clear_config([Pleroma.Upload, :base_url], "https://s3.amazonaws.com") +      clear_config([Pleroma.Uploaders.S3, :bucket], "test_bucket")        user = insert(:user, %{nickname: "cofe", name: "Cofe", ap_id: "http://cofe.io/users/cofe"}) @@ -219,7 +215,8 @@ defmodule Pleroma.User.BackupTest do      end      test "S3", %{path: path, backup: backup} do -      Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.S3) +      clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.S3) +      clear_config([Pleroma.Uploaders.S3, :streaming_enabled], false)        with_mock ExAws,          request: fn @@ -229,13 +226,10 @@ defmodule Pleroma.User.BackupTest do          assert {:ok, %Pleroma.Upload{}} = Backup.upload(backup, path)          assert {:ok, _backup} = Backup.delete(backup)        end - -      with_mock ExAws, request: fn %{http_method: :delete} -> {:ok, %{status_code: 204}} end do -      end      end      test "Local", %{path: path, backup: backup} do -      Pleroma.Config.put([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local) +      clear_config([Pleroma.Upload, :uploader], Pleroma.Uploaders.Local)        assert {:ok, %Pleroma.Upload{}} = Backup.upload(backup, path)        assert {:ok, _backup} = Backup.delete(backup) diff --git a/test/pleroma/user/import_test.exs b/test/pleroma/user/import_test.exs index e198cdc08..a84fce337 100644 --- a/test/pleroma/user/import_test.exs +++ b/test/pleroma/user/import_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.User.ImportTest do diff --git a/test/pleroma/user/notification_setting_test.exs b/test/pleroma/user/notification_setting_test.exs index 308da216a..6cb8803d9 100644 --- a/test/pleroma/user/notification_setting_test.exs +++ b/test/pleroma/user/notification_setting_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.User.NotificationSettingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.User.NotificationSetting diff --git a/test/pleroma/user/query_test.exs b/test/pleroma/user/query_test.exs index e2f5c7d81..357016e3e 100644 --- a/test/pleroma/user/query_test.exs +++ b/test/pleroma/user/query_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.User.QueryTest do diff --git a/test/pleroma/user/welcome_chat_message_test.exs b/test/pleroma/user/welcome_chat_message_test.exs index fe26d6e4d..42a45fa19 100644 --- a/test/pleroma/user/welcome_chat_message_test.exs +++ b/test/pleroma/user/welcome_chat_message_test.exs @@ -1,11 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.User.WelcomeChatMessageTest do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.User.WelcomeChatMessage    import Pleroma.Factory @@ -17,10 +16,10 @@ defmodule Pleroma.User.WelcomeChatMessageTest do        welcome_user = insert(:user, name: "mewmew")        user = insert(:user) -      Config.put([:welcome, :chat_message, :enabled], true) -      Config.put([:welcome, :chat_message, :sender_nickname], welcome_user.nickname) +      clear_config([:welcome, :chat_message, :enabled], true) +      clear_config([:welcome, :chat_message, :sender_nickname], welcome_user.nickname) -      Config.put( +      clear_config(          [:welcome, :chat_message, :message],          "Hello, welcome to Blob/Cat!"        ) @@ -28,8 +27,10 @@ defmodule Pleroma.User.WelcomeChatMessageTest do        {:ok, %Pleroma.Activity{} = activity} = WelcomeChatMessage.post_message(user)        assert user.ap_id in activity.recipients -      assert Pleroma.Object.normalize(activity).data["type"] == "ChatMessage" -      assert Pleroma.Object.normalize(activity).data["content"] == "Hello, welcome to Blob/Cat!" +      assert Pleroma.Object.normalize(activity, fetch: false).data["type"] == "ChatMessage" + +      assert Pleroma.Object.normalize(activity, fetch: false).data["content"] == +               "Hello, welcome to Blob/Cat!"      end    end  end diff --git a/test/pleroma/user/welcome_email_test.exs b/test/pleroma/user/welcome_email_test.exs index d005d11b2..c3d383a7f 100644 --- a/test/pleroma/user/welcome_email_test.exs +++ b/test/pleroma/user/welcome_email_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.User.WelcomeEmailTest do @@ -18,15 +18,15 @@ defmodule Pleroma.User.WelcomeEmailTest do      test "send a welcome email" do        user = insert(:user, name: "Jimm") -      Config.put([:welcome, :email, :enabled], true) -      Config.put([:welcome, :email, :sender], "welcome@pleroma.app") +      clear_config([:welcome, :email, :enabled], true) +      clear_config([:welcome, :email, :sender], "welcome@pleroma.app") -      Config.put( +      clear_config(          [:welcome, :email, :subject],          "Hello, welcome to pleroma: <%= instance_name %>"        ) -      Config.put( +      clear_config(          [:welcome, :email, :html],          "<h1>Hello <%= user.name %>.</h1> <p>Welcome to <%= instance_name %></p>"        ) @@ -44,7 +44,7 @@ defmodule Pleroma.User.WelcomeEmailTest do          html_body: "<h1>Hello #{user.name}.</h1> <p>Welcome to #{instance_name}</p>"        ) -      Config.put([:welcome, :email, :sender], {"Pleroma App", "welcome@pleroma.app"}) +      clear_config([:welcome, :email, :sender], {"Pleroma App", "welcome@pleroma.app"})        {:ok, _job} = WelcomeEmail.send_email(user) diff --git a/test/pleroma/user/welcome_message_test.exs b/test/pleroma/user/welcome_message_test.exs index 3cd6f5cb7..28afde943 100644 --- a/test/pleroma/user/welcome_message_test.exs +++ b/test/pleroma/user/welcome_message_test.exs @@ -1,11 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.User.WelcomeMessageTest do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.User.WelcomeMessage    import Pleroma.Factory @@ -17,10 +16,10 @@ defmodule Pleroma.User.WelcomeMessageTest do        welcome_user = insert(:user)        user = insert(:user, name: "Jimm") -      Config.put([:welcome, :direct_message, :enabled], true) -      Config.put([:welcome, :direct_message, :sender_nickname], welcome_user.nickname) +      clear_config([:welcome, :direct_message, :enabled], true) +      clear_config([:welcome, :direct_message, :sender_nickname], welcome_user.nickname) -      Config.put( +      clear_config(          [:welcome, :direct_message, :message],          "Hello. Welcome to Pleroma"        ) @@ -28,7 +27,9 @@ defmodule Pleroma.User.WelcomeMessageTest do        {:ok, %Pleroma.Activity{} = activity} = WelcomeMessage.post_message(user)        assert user.ap_id in activity.recipients        assert activity.data["directMessage"] == true -      assert Pleroma.Object.normalize(activity).data["content"] =~ "Hello. Welcome to Pleroma" + +      assert Pleroma.Object.normalize(activity, fetch: false).data["content"] =~ +               "Hello. Welcome to Pleroma"      end    end  end diff --git a/test/pleroma/user_invite_token_test.exs b/test/pleroma/user_invite_token_test.exs index 63f18f13c..233d4e864 100644 --- a/test/pleroma/user_invite_token_test.exs +++ b/test/pleroma/user_invite_token_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.UserInviteTokenTest do diff --git a/test/pleroma/user_relationship_test.exs b/test/pleroma/user_relationship_test.exs index f12406097..b2b074607 100644 --- a/test/pleroma/user_relationship_test.exs +++ b/test/pleroma/user_relationship_test.exs @@ -1,11 +1,11 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.UserRelationshipTest do    alias Pleroma.UserRelationship -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/user_search_test.exs b/test/pleroma/user_search_test.exs index accb0b816..69167bb0c 100644 --- a/test/pleroma/user_search_test.exs +++ b/test/pleroma/user_search_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.UserSearchTest do @@ -18,7 +18,7 @@ defmodule Pleroma.UserSearchTest do      setup do: clear_config([:instance, :limit_to_local_content])      test "returns a resolved user as the first result" do -      Pleroma.Config.put([:instance, :limit_to_local_content], false) +      clear_config([:instance, :limit_to_local_content], false)        user = insert(:user, %{nickname: "no_relation", ap_id: "https://lain.com/users/lain"})        _user = insert(:user, %{nickname: "com_user"}) @@ -199,7 +199,7 @@ defmodule Pleroma.UserSearchTest do      end      test "find only local users for authenticated users when `limit_to_local_content` is `:all`" do -      Pleroma.Config.put([:instance, :limit_to_local_content], :all) +      clear_config([:instance, :limit_to_local_content], :all)        %{id: id} = insert(:user, %{name: "lain"})        insert(:user, %{name: "ebn", nickname: "lain@mastodon.social", local: false}) @@ -209,7 +209,7 @@ defmodule Pleroma.UserSearchTest do      end      test "find all users for unauthenticated users when `limit_to_local_content` is `false`" do -      Pleroma.Config.put([:instance, :limit_to_local_content], false) +      clear_config([:instance, :limit_to_local_content], false)        u1 = insert(:user, %{name: "lain"})        u2 = insert(:user, %{name: "ebn", nickname: "lain@mastodon.social", local: false}) diff --git a/test/pleroma/user_test.exs b/test/pleroma/user_test.exs index 5d544fe7d..d81c1b8eb 100644 --- a/test/pleroma/user_test.exs +++ b/test/pleroma/user_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.UserTest do @@ -202,11 +202,11 @@ defmodule Pleroma.UserTest do    test "doesn't return follow requests for deactivated accounts" do      locked = insert(:user, is_locked: true) -    pending_follower = insert(:user, %{deactivated: true}) +    pending_follower = insert(:user, %{is_active: false})      CommonAPI.follow(pending_follower, locked) -    assert true == pending_follower.deactivated +    refute pending_follower.is_active      assert [] = User.get_follow_requests(locked)    end @@ -275,7 +275,7 @@ defmodule Pleroma.UserTest do    test "can't follow a deactivated users" do      user = insert(:user) -    followed = insert(:user, %{deactivated: true}) +    followed = insert(:user, %{is_active: false})      {:error, _} = User.follow(user, followed)    end @@ -311,7 +311,7 @@ defmodule Pleroma.UserTest do      setup do: clear_config([:instance, :external_user_synchronization])      test "unfollow with syncronizes external user" do -      Pleroma.Config.put([:instance, :external_user_synchronization], true) +      clear_config([:instance, :external_user_synchronization], true)        followed =          insert(:user, @@ -396,7 +396,7 @@ defmodule Pleroma.UserTest do        user = insert(:user)        remote_user = insert(:user, %{local: false}) -      Pleroma.Config.put([:instance, :autofollowed_nicknames], [ +      clear_config([:instance, :autofollowed_nicknames], [          user.nickname,          remote_user.nickname        ]) @@ -413,7 +413,7 @@ defmodule Pleroma.UserTest do        user1 = insert(:user)        user2 = insert(:user) -      Pleroma.Config.put([:instance, :autofollowing_nicknames], [ +      clear_config([:instance, :autofollowing_nicknames], [          user1.nickname,          user2.nickname        ]) @@ -428,9 +428,9 @@ defmodule Pleroma.UserTest do      test "it sends a welcome message if it is set" do        welcome_user = insert(:user) -      Pleroma.Config.put([:welcome, :direct_message, :enabled], true) -      Pleroma.Config.put([:welcome, :direct_message, :sender_nickname], welcome_user.nickname) -      Pleroma.Config.put([:welcome, :direct_message, :message], "Hello, this is a direct message") +      clear_config([:welcome, :direct_message, :enabled], true) +      clear_config([:welcome, :direct_message, :sender_nickname], welcome_user.nickname) +      clear_config([:welcome, :direct_message, :message], "Hello, this is a direct message")        cng = User.register_changeset(%User{}, @full_user_data)        {:ok, registered_user} = User.register(cng) @@ -438,15 +438,15 @@ defmodule Pleroma.UserTest do        activity = Repo.one(Pleroma.Activity)        assert registered_user.ap_id in activity.recipients -      assert Object.normalize(activity).data["content"] =~ "direct message" +      assert Object.normalize(activity, fetch: false).data["content"] =~ "direct message"        assert activity.actor == welcome_user.ap_id      end      test "it sends a welcome chat message if it is set" do        welcome_user = insert(:user) -      Pleroma.Config.put([:welcome, :chat_message, :enabled], true) -      Pleroma.Config.put([:welcome, :chat_message, :sender_nickname], welcome_user.nickname) -      Pleroma.Config.put([:welcome, :chat_message, :message], "Hello, this is a chat message") +      clear_config([:welcome, :chat_message, :enabled], true) +      clear_config([:welcome, :chat_message, :sender_nickname], welcome_user.nickname) +      clear_config([:welcome, :chat_message, :message], "Hello, this is a chat message")        cng = User.register_changeset(%User{}, @full_user_data)        {:ok, registered_user} = User.register(cng) @@ -454,7 +454,7 @@ defmodule Pleroma.UserTest do        activity = Repo.one(Pleroma.Activity)        assert registered_user.ap_id in activity.recipients -      assert Object.normalize(activity).data["content"] =~ "chat message" +      assert Object.normalize(activity, fetch: false).data["content"] =~ "chat message"        assert activity.actor == welcome_user.ap_id      end @@ -480,12 +480,12 @@ defmodule Pleroma.UserTest do              )      test "it sends a welcome chat message when Simple policy applied to local instance" do -      Pleroma.Config.put([:mrf_simple, :media_nsfw], ["localhost"]) +      clear_config([:mrf_simple, :media_nsfw], ["localhost"])        welcome_user = insert(:user) -      Pleroma.Config.put([:welcome, :chat_message, :enabled], true) -      Pleroma.Config.put([:welcome, :chat_message, :sender_nickname], welcome_user.nickname) -      Pleroma.Config.put([:welcome, :chat_message, :message], "Hello, this is a chat message") +      clear_config([:welcome, :chat_message, :enabled], true) +      clear_config([:welcome, :chat_message, :sender_nickname], welcome_user.nickname) +      clear_config([:welcome, :chat_message, :message], "Hello, this is a chat message")        cng = User.register_changeset(%User{}, @full_user_data)        {:ok, registered_user} = User.register(cng) @@ -493,16 +493,16 @@ defmodule Pleroma.UserTest do        activity = Repo.one(Pleroma.Activity)        assert registered_user.ap_id in activity.recipients -      assert Object.normalize(activity).data["content"] =~ "chat message" +      assert Object.normalize(activity, fetch: false).data["content"] =~ "chat message"        assert activity.actor == welcome_user.ap_id      end      test "it sends a welcome email message if it is set" do        welcome_user = insert(:user) -      Pleroma.Config.put([:welcome, :email, :enabled], true) -      Pleroma.Config.put([:welcome, :email, :sender], welcome_user.email) +      clear_config([:welcome, :email, :enabled], true) +      clear_config([:welcome, :email, :sender], welcome_user.email) -      Pleroma.Config.put( +      clear_config(          [:welcome, :email, :subject],          "Hello, welcome to cool site: <%= instance_name %>"        ) @@ -522,7 +522,7 @@ defmodule Pleroma.UserTest do      end      test "it sends a confirm email" do -      Pleroma.Config.put([:instance, :account_activation_required], true) +      clear_config([:instance, :account_activation_required], true)        cng = User.register_changeset(%User{}, @full_user_data)        {:ok, registered_user} = User.register(cng) @@ -535,8 +535,45 @@ defmodule Pleroma.UserTest do        |> assert_email_sent()      end +    test "sends a pending approval email" do +      clear_config([:instance, :account_approval_required], true) + +      {:ok, user} = +        User.register_changeset(%User{}, @full_user_data) +        |> User.register() + +      ObanHelpers.perform_all() + +      assert_email_sent( +        from: Pleroma.Config.Helpers.sender(), +        to: {user.name, user.email}, +        subject: "Your account is awaiting approval" +      ) +    end + +    test "it sends a registration confirmed email if no others will be sent" do +      clear_config([:welcome, :email, :enabled], false) +      clear_config([:instance, :account_activation_required], false) +      clear_config([:instance, :account_approval_required], false) + +      {:ok, user} = +        User.register_changeset(%User{}, @full_user_data) +        |> User.register() + +      ObanHelpers.perform_all() + +      instance_name = Pleroma.Config.get([:instance, :name]) +      sender = Pleroma.Config.get([:instance, :notify_email]) + +      assert_email_sent( +        from: {instance_name, sender}, +        to: {user.name, user.email}, +        subject: "Account registered on #{instance_name}" +      ) +    end +      test "it requires an email, name, nickname and password, bio is optional when account_activation_required is enabled" do -      Pleroma.Config.put([:instance, :account_activation_required], true) +      clear_config([:instance, :account_activation_required], true)        @full_user_data        |> Map.keys() @@ -549,7 +586,7 @@ defmodule Pleroma.UserTest do      end      test "it requires an name, nickname and password, bio and email are optional when account_activation_required is disabled" do -      Pleroma.Config.put([:instance, :account_activation_required], false) +      clear_config([:instance, :account_activation_required], false)        @full_user_data        |> Map.keys() @@ -624,7 +661,7 @@ defmodule Pleroma.UserTest do        {:ok, user} = Repo.insert(changeset) -      refute user.confirmation_pending +      assert user.is_confirmed      end    end @@ -645,17 +682,17 @@ defmodule Pleroma.UserTest do        {:ok, user} = Repo.insert(changeset) -      assert user.confirmation_pending +      refute user.is_confirmed        assert user.confirmation_token      end      test "it creates confirmed user if :confirmed option is given" do -      changeset = User.register_changeset(%User{}, @full_user_data, need_confirmation: false) +      changeset = User.register_changeset(%User{}, @full_user_data, confirmed: true)        assert changeset.valid?        {:ok, user} = Repo.insert(changeset) -      refute user.confirmation_pending +      assert user.is_confirmed        refute user.confirmation_token      end    end @@ -678,7 +715,7 @@ defmodule Pleroma.UserTest do        {:ok, user} = Repo.insert(changeset) -      assert user.approval_pending +      refute user.is_approved        assert user.registration_reason == "I'm a cool guy :)"      end @@ -1297,14 +1334,14 @@ defmodule Pleroma.UserTest do      end    end -  describe ".deactivate" do +  describe ".set_activation" do      test "can de-activate then re-activate a user" do        user = insert(:user) -      assert false == user.deactivated -      {:ok, user} = User.deactivate(user) -      assert true == user.deactivated -      {:ok, user} = User.deactivate(user, false) -      assert false == user.deactivated +      assert user.is_active +      {:ok, user} = User.set_activation(user, false) +      refute user.is_active +      {:ok, user} = User.set_activation(user, true) +      assert user.is_active      end      test "hide a user from followers" do @@ -1312,7 +1349,7 @@ defmodule Pleroma.UserTest do        user2 = insert(:user)        {:ok, user, user2} = User.follow(user, user2) -      {:ok, _user} = User.deactivate(user) +      {:ok, _user} = User.set_activation(user, false)        user2 = User.get_cached_by_id(user2.id) @@ -1328,7 +1365,7 @@ defmodule Pleroma.UserTest do        assert user2.following_count == 1        assert User.following_count(user2) == 1 -      {:ok, _user} = User.deactivate(user) +      {:ok, _user} = User.set_activation(user, false)        user2 = User.get_cached_by_id(user2.id) @@ -1358,7 +1395,7 @@ defmodule Pleroma.UserTest do                   user: user2                 }) -      {:ok, _user} = User.deactivate(user) +      {:ok, _user} = User.set_activation(user, false)        assert [] == ActivityPub.fetch_public_activities(%{})        assert [] == Pleroma.Notification.for_user(user2) @@ -1372,17 +1409,17 @@ defmodule Pleroma.UserTest do    describe "approve" do      test "approves a user" do -      user = insert(:user, approval_pending: true) -      assert true == user.approval_pending +      user = insert(:user, is_approved: false) +      refute user.is_approved        {:ok, user} = User.approve(user) -      assert false == user.approval_pending +      assert user.is_approved      end      test "approves a list of users" do        unapproved_users = [ -        insert(:user, approval_pending: true), -        insert(:user, approval_pending: true), -        insert(:user, approval_pending: true) +        insert(:user, is_approved: false), +        insert(:user, is_approved: false), +        insert(:user, is_approved: false)        ]        {:ok, users} = User.approve(unapproved_users) @@ -1390,9 +1427,101 @@ defmodule Pleroma.UserTest do        assert Enum.count(users) == 3        Enum.each(users, fn user -> -        assert false == user.approval_pending +        assert user.is_approved        end)      end + +    test "it sends welcome email if it is set" do +      clear_config([:welcome, :email, :enabled], true) +      clear_config([:welcome, :email, :sender], "tester@test.me") + +      user = insert(:user, is_approved: false) +      welcome_user = insert(:user, email: "tester@test.me") +      instance_name = Pleroma.Config.get([:instance, :name]) + +      User.approve(user) + +      ObanHelpers.perform_all() + +      assert_email_sent( +        from: {instance_name, welcome_user.email}, +        to: {user.name, user.email}, +        html_body: "Welcome to #{instance_name}" +      ) +    end + +    test "approving an approved user does not trigger post-register actions" do +      clear_config([:welcome, :email, :enabled], true) + +      user = insert(:user, is_approved: true) +      User.approve(user) + +      ObanHelpers.perform_all() + +      assert_no_email_sent() +    end +  end + +  describe "confirm" do +    test "confirms a user" do +      user = insert(:user, is_confirmed: false) +      refute user.is_confirmed +      {:ok, user} = User.confirm(user) +      assert user.is_confirmed +    end + +    test "confirms a list of users" do +      unconfirmed_users = [ +        insert(:user, is_confirmed: false), +        insert(:user, is_confirmed: false), +        insert(:user, is_confirmed: false) +      ] + +      {:ok, users} = User.confirm(unconfirmed_users) + +      assert Enum.count(users) == 3 + +      Enum.each(users, fn user -> +        assert user.is_confirmed +      end) +    end + +    test "sends approval emails when `is_approved: false`" do +      admin = insert(:user, is_admin: true) +      user = insert(:user, is_confirmed: false, is_approved: false) +      User.confirm(user) + +      ObanHelpers.perform_all() + +      user_email = Pleroma.Emails.UserEmail.approval_pending_email(user) +      admin_email = Pleroma.Emails.AdminEmail.new_unapproved_registration(admin, user) + +      notify_email = Pleroma.Config.get([:instance, :notify_email]) +      instance_name = Pleroma.Config.get([:instance, :name]) + +      # User approval email +      assert_email_sent( +        from: {instance_name, notify_email}, +        to: {user.name, user.email}, +        html_body: user_email.html_body +      ) + +      # Admin email +      assert_email_sent( +        from: {instance_name, notify_email}, +        to: {admin.name, admin.email}, +        html_body: admin_email.html_body +      ) +    end + +    test "confirming a confirmed user does not trigger post-register actions" do +      user = insert(:user, is_confirmed: true, is_approved: false) +      User.confirm(user) + +      ObanHelpers.perform_all() + +      assert_no_email_sent() +    end    end    describe "delete" do @@ -1436,7 +1565,7 @@ defmodule Pleroma.UserTest do        follower = User.get_cached_by_id(follower.id)        refute User.following?(follower, user) -      assert %{deactivated: true} = User.get_by_id(user.id) +      assert %{is_active: false} = User.get_by_id(user.id)        assert [] == User.get_follow_requests(locked_user) @@ -1455,35 +1584,19 @@ defmodule Pleroma.UserTest do      end    end -  describe "delete/1 when confirmation is pending" do -    setup do -      user = insert(:user, confirmation_pending: true) -      {:ok, user: user} -    end +  test "delete/1 when confirmation is pending deletes the user" do +    clear_config([:instance, :account_activation_required], true) +    user = insert(:user, is_confirmed: false) -    test "deletes user from database when activation required", %{user: user} do -      clear_config([:instance, :account_activation_required], true) - -      {:ok, job} = User.delete(user) -      {:ok, _} = ObanHelpers.perform(job) - -      refute User.get_cached_by_id(user.id) -      refute User.get_by_id(user.id) -    end - -    test "deactivates user when activation is not required", %{user: user} do -      clear_config([:instance, :account_activation_required], false) - -      {:ok, job} = User.delete(user) -      {:ok, _} = ObanHelpers.perform(job) +    {:ok, job} = User.delete(user) +    {:ok, _} = ObanHelpers.perform(job) -      assert %{deactivated: true} = User.get_cached_by_id(user.id) -      assert %{deactivated: true} = User.get_by_id(user.id) -    end +    refute User.get_cached_by_id(user.id) +    refute User.get_by_id(user.id)    end    test "delete/1 when approval is pending deletes the user" do -    user = insert(:user, approval_pending: true) +    user = insert(:user, is_approved: false)      {:ok, job} = User.delete(user)      {:ok, _} = ObanHelpers.perform(job) @@ -1508,13 +1621,13 @@ defmodule Pleroma.UserTest do          follower_count: 9,          following_count: 9001,          is_locked: true, -        confirmation_pending: true, +        is_confirmed: false,          password_reset_pending: true, -        approval_pending: true, +        is_approved: false,          registration_reason: "ahhhhh",          confirmation_token: "qqqq",          domain_blocks: ["lain.com"], -        deactivated: true, +        is_active: false,          ap_enabled: true,          is_moderator: true,          is_admin: true, @@ -1550,13 +1663,13 @@ defmodule Pleroma.UserTest do               follower_count: 0,               following_count: 0,               is_locked: false, -             confirmation_pending: false, +             is_confirmed: true,               password_reset_pending: false, -             approval_pending: false, +             is_approved: true,               registration_reason: nil,               confirmation_token: nil,               domain_blocks: [], -             deactivated: true, +             is_active: false,               ap_enabled: false,               is_moderator: false,               is_admin: false, @@ -1620,14 +1733,14 @@ defmodule Pleroma.UserTest do      setup do: clear_config([:instance, :account_activation_required])      test "return confirmation_pending for unconfirm user" do -      Pleroma.Config.put([:instance, :account_activation_required], true) -      user = insert(:user, confirmation_pending: true) +      clear_config([:instance, :account_activation_required], true) +      user = insert(:user, is_confirmed: false)        assert User.account_status(user) == :confirmation_pending      end      test "return active for confirmed user" do -      Pleroma.Config.put([:instance, :account_activation_required], true) -      user = insert(:user, confirmation_pending: false) +      clear_config([:instance, :account_activation_required], true) +      user = insert(:user, is_confirmed: true)        assert User.account_status(user) == :active      end @@ -1642,15 +1755,15 @@ defmodule Pleroma.UserTest do      end      test "returns :deactivated for deactivated user" do -      user = insert(:user, local: true, confirmation_pending: false, deactivated: true) +      user = insert(:user, local: true, is_confirmed: true, is_active: false)        assert User.account_status(user) == :deactivated      end      test "returns :approval_pending for unapproved user" do -      user = insert(:user, local: true, approval_pending: true) +      user = insert(:user, local: true, is_approved: false)        assert User.account_status(user) == :approval_pending -      user = insert(:user, local: true, confirmation_pending: true, approval_pending: true) +      user = insert(:user, local: true, is_confirmed: false, is_approved: false)        assert User.account_status(user) == :approval_pending      end    end @@ -1705,34 +1818,27 @@ defmodule Pleroma.UserTest do      end      test "returns false when the account is unconfirmed and confirmation is required" do -      Pleroma.Config.put([:instance, :account_activation_required], true) +      clear_config([:instance, :account_activation_required], true) -      user = insert(:user, local: true, confirmation_pending: true) +      user = insert(:user, local: true, is_confirmed: false)        other_user = insert(:user, local: true)        refute User.visible_for(user, other_user) == :visible      end      test "returns true when the account is unconfirmed and confirmation is required but the account is remote" do -      Pleroma.Config.put([:instance, :account_activation_required], true) - -      user = insert(:user, local: false, confirmation_pending: true) -      other_user = insert(:user, local: true) - -      assert User.visible_for(user, other_user) == :visible -    end +      clear_config([:instance, :account_activation_required], true) -    test "returns true when the account is unconfirmed and confirmation is not required" do -      user = insert(:user, local: true, confirmation_pending: true) +      user = insert(:user, local: false, is_confirmed: false)        other_user = insert(:user, local: true)        assert User.visible_for(user, other_user) == :visible      end      test "returns true when the account is unconfirmed and being viewed by a privileged account (confirmation required)" do -      Pleroma.Config.put([:instance, :account_activation_required], true) +      clear_config([:instance, :account_activation_required], true) -      user = insert(:user, local: true, confirmation_pending: true) +      user = insert(:user, local: true, is_confirmed: false)        other_user = insert(:user, local: true, is_admin: true)        assert User.visible_for(user, other_user) == :visible @@ -1800,7 +1906,7 @@ defmodule Pleroma.UserTest do        users =          Enum.map(1..total, fn _ -> -          insert(:user, last_digest_emailed_at: days_ago(20), deactivated: false) +          insert(:user, last_digest_emailed_at: days_ago(20), is_active: true)          end)        inactive_users_ids = @@ -1818,7 +1924,7 @@ defmodule Pleroma.UserTest do        users =          Enum.map(1..total, fn _ -> -          insert(:user, last_digest_emailed_at: days_ago(20), deactivated: false) +          insert(:user, last_digest_emailed_at: days_ago(20), is_active: true)          end)        {inactive, active} = Enum.split(users, trunc(total / 2)) @@ -1851,7 +1957,7 @@ defmodule Pleroma.UserTest do        users =          Enum.map(1..total, fn _ -> -          insert(:user, last_digest_emailed_at: days_ago(20), deactivated: false) +          insert(:user, last_digest_emailed_at: days_ago(20), is_active: true)          end)        [sender | recipients] = users @@ -1889,24 +1995,6 @@ defmodule Pleroma.UserTest do      end    end -  describe "toggle_confirmation/1" do -    test "if user is confirmed" do -      user = insert(:user, confirmation_pending: false) -      {:ok, user} = User.toggle_confirmation(user) - -      assert user.confirmation_pending -      assert user.confirmation_token -    end - -    test "if user is unconfirmed" do -      user = insert(:user, confirmation_pending: true, confirmation_token: "some token") -      {:ok, user} = User.toggle_confirmation(user) - -      refute user.confirmation_pending -      refute user.confirmation_token -    end -  end -    describe "ensure_keys_present" do      test "it creates keys for a user and stores them in info" do        user = insert(:user) @@ -1939,7 +2027,7 @@ defmodule Pleroma.UserTest do        user1 = insert(:user, local: false, ap_id: "http://localhost:4001/users/masto_closed")        user2 = insert(:user, local: false, ap_id: "http://localhost:4001/users/fuser2")        insert(:user, local: true) -      insert(:user, local: false, deactivated: true) +      insert(:user, local: false, is_active: false)        {:ok, user1: user1, user2: user2}      end @@ -2005,7 +2093,7 @@ defmodule Pleroma.UserTest do      setup do: clear_config([:instance, :external_user_synchronization])      test "updates the counters normally on following/getting a follow when disabled" do -      Pleroma.Config.put([:instance, :external_user_synchronization], false) +      clear_config([:instance, :external_user_synchronization], false)        user = insert(:user)        other_user = @@ -2026,7 +2114,7 @@ defmodule Pleroma.UserTest do      end      test "syncronizes the counters with the remote instance for the followed when enabled" do -      Pleroma.Config.put([:instance, :external_user_synchronization], false) +      clear_config([:instance, :external_user_synchronization], false)        user = insert(:user) @@ -2041,14 +2129,14 @@ defmodule Pleroma.UserTest do        assert other_user.following_count == 0        assert other_user.follower_count == 0 -      Pleroma.Config.put([:instance, :external_user_synchronization], true) +      clear_config([:instance, :external_user_synchronization], true)        {:ok, _user, other_user} = User.follow(user, other_user)        assert other_user.follower_count == 437      end      test "syncronizes the counters with the remote instance for the follower when enabled" do -      Pleroma.Config.put([:instance, :external_user_synchronization], false) +      clear_config([:instance, :external_user_synchronization], false)        user = insert(:user) @@ -2063,7 +2151,7 @@ defmodule Pleroma.UserTest do        assert other_user.following_count == 0        assert other_user.follower_count == 0 -      Pleroma.Config.put([:instance, :external_user_synchronization], true) +      clear_config([:instance, :external_user_synchronization], true)        {:ok, other_user, _user} = User.follow(other_user, user)        assert other_user.following_count == 152 @@ -2110,43 +2198,43 @@ defmodule Pleroma.UserTest do      test "allows getting remote users by id no matter what :limit_to_local_content is set to", %{        remote_user: remote_user      } do -      Pleroma.Config.put([:instance, :limit_to_local_content], false) +      clear_config([:instance, :limit_to_local_content], false)        assert %User{} = User.get_cached_by_nickname_or_id(remote_user.id) -      Pleroma.Config.put([:instance, :limit_to_local_content], true) +      clear_config([:instance, :limit_to_local_content], true)        assert %User{} = User.get_cached_by_nickname_or_id(remote_user.id) -      Pleroma.Config.put([:instance, :limit_to_local_content], :unauthenticated) +      clear_config([:instance, :limit_to_local_content], :unauthenticated)        assert %User{} = User.get_cached_by_nickname_or_id(remote_user.id)      end      test "disallows getting remote users by nickname without authentication when :limit_to_local_content is set to :unauthenticated",           %{remote_user: remote_user} do -      Pleroma.Config.put([:instance, :limit_to_local_content], :unauthenticated) +      clear_config([:instance, :limit_to_local_content], :unauthenticated)        assert nil == User.get_cached_by_nickname_or_id(remote_user.nickname)      end      test "allows getting remote users by nickname with authentication when :limit_to_local_content is set to :unauthenticated",           %{remote_user: remote_user, local_user: local_user} do -      Pleroma.Config.put([:instance, :limit_to_local_content], :unauthenticated) +      clear_config([:instance, :limit_to_local_content], :unauthenticated)        assert %User{} = User.get_cached_by_nickname_or_id(remote_user.nickname, for: local_user)      end      test "disallows getting remote users by nickname when :limit_to_local_content is set to true",           %{remote_user: remote_user} do -      Pleroma.Config.put([:instance, :limit_to_local_content], true) +      clear_config([:instance, :limit_to_local_content], true)        assert nil == User.get_cached_by_nickname_or_id(remote_user.nickname)      end      test "allows getting local users by nickname no matter what :limit_to_local_content is set to",           %{local_user: local_user} do -      Pleroma.Config.put([:instance, :limit_to_local_content], false) +      clear_config([:instance, :limit_to_local_content], false)        assert %User{} = User.get_cached_by_nickname_or_id(local_user.nickname) -      Pleroma.Config.put([:instance, :limit_to_local_content], true) +      clear_config([:instance, :limit_to_local_content], true)        assert %User{} = User.get_cached_by_nickname_or_id(local_user.nickname) -      Pleroma.Config.put([:instance, :limit_to_local_content], :unauthenticated) +      clear_config([:instance, :limit_to_local_content], :unauthenticated)        assert %User{} = User.get_cached_by_nickname_or_id(local_user.nickname)      end    end @@ -2165,6 +2253,36 @@ defmodule Pleroma.UserTest do      end    end +  describe "local_nickname/1" do +    test "returns nickname without host" do +      assert User.local_nickname("@mentioned") == "mentioned" +      assert User.local_nickname("a_local_nickname") == "a_local_nickname" +      assert User.local_nickname("nickname@host.com") == "nickname" +    end +  end + +  describe "full_nickname/1" do +    test "returns fully qualified nickname for local and remote users" do +      local_user = +        insert(:user, nickname: "local_user", ap_id: "https://somehost.com/users/local_user") + +      remote_user = insert(:user, nickname: "remote@host.com", local: false) + +      assert User.full_nickname(local_user) == "local_user@somehost.com" +      assert User.full_nickname(remote_user) == "remote@host.com" +    end + +    test "strips leading @ from mentions" do +      assert User.full_nickname("@mentioned") == "mentioned" +      assert User.full_nickname("@nickname@host.com") == "nickname@host.com" +    end + +    test "does not modify nicknames" do +      assert User.full_nickname("nickname") == "nickname" +      assert User.full_nickname("nickname@host.com") == "nickname@host.com" +    end +  end +    test "avatar fallback" do      user = insert(:user)      assert User.avatar_url(user) =~ "/images/avi.png" @@ -2181,4 +2299,88 @@ defmodule Pleroma.UserTest do      user = insert(:user, ap_id: "https://lain.com/users/lain", nickname: "lain")      assert User.get_host(user) == "lain.com"    end + +  test "update_last_active_at/1" do +    user = insert(:user) +    assert is_nil(user.last_active_at) + +    test_started_at = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + +    assert {:ok, user} = User.update_last_active_at(user) + +    assert user.last_active_at >= test_started_at +    assert user.last_active_at <= NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second) + +    last_active_at = +      NaiveDateTime.utc_now() +      |> NaiveDateTime.add(-:timer.hours(24), :millisecond) +      |> NaiveDateTime.truncate(:second) + +    assert {:ok, user} = +             user +             |> cast(%{last_active_at: last_active_at}, [:last_active_at]) +             |> User.update_and_set_cache() + +    assert user.last_active_at == last_active_at +    assert {:ok, user} = User.update_last_active_at(user) +    assert user.last_active_at >= test_started_at +    assert user.last_active_at <= NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second) +  end + +  test "active_user_count/1" do +    insert(:user) +    insert(:user, %{local: false}) +    insert(:user, %{last_active_at: Timex.shift(NaiveDateTime.utc_now(), weeks: -5)}) +    insert(:user, %{last_active_at: Timex.shift(NaiveDateTime.utc_now(), weeks: -3)}) +    insert(:user, %{last_active_at: NaiveDateTime.utc_now()}) + +    assert User.active_user_count() == 2 +    assert User.active_user_count(6) == 3 +    assert User.active_user_count(1) == 1 +  end + +  describe "pins" do +    setup do +      user = insert(:user) + +      [user: user, object_id: object_id_from_created_activity(user)] +    end + +    test "unique pins", %{user: user, object_id: object_id} do +      assert {:ok, %{pinned_objects: %{^object_id => pinned_at1} = pins} = updated_user} = +               User.add_pinned_object_id(user, object_id) + +      assert Enum.count(pins) == 1 + +      assert {:ok, %{pinned_objects: %{^object_id => pinned_at2} = pins}} = +               User.add_pinned_object_id(updated_user, object_id) + +      assert pinned_at1 == pinned_at2 + +      assert Enum.count(pins) == 1 +    end + +    test "respects max_pinned_statuses limit", %{user: user, object_id: object_id} do +      clear_config([:instance, :max_pinned_statuses], 1) +      {:ok, updated} = User.add_pinned_object_id(user, object_id) + +      object_id2 = object_id_from_created_activity(user) + +      {:error, %{errors: errors}} = User.add_pinned_object_id(updated, object_id2) +      assert Keyword.has_key?(errors, :pinned_objects) +    end + +    test "remove_pinned_object_id/2", %{user: user, object_id: object_id} do +      assert {:ok, updated} = User.add_pinned_object_id(user, object_id) + +      {:ok, after_remove} = User.remove_pinned_object_id(updated, object_id) +      assert after_remove.pinned_objects == %{} +    end +  end + +  defp object_id_from_created_activity(user) do +    %{id: id} = insert(:note_activity, user: user) +    %{object: %{data: %{"id" => object_id}}} = Activity.get_by_id_with_object(id) +    object_id +  end  end diff --git a/test/pleroma/utils_test.exs b/test/pleroma/utils_test.exs index 460f7e0b5..c593a9490 100644 --- a/test/pleroma/utils_test.exs +++ b/test/pleroma/utils_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.UtilsTest do diff --git a/test/pleroma/web/activity_pub/activity_pub_controller_test.exs b/test/pleroma/web/activity_pub/activity_pub_controller_test.exs index 0063d0482..cea4b3a97 100644 --- a/test/pleroma/web/activity_pub/activity_pub_controller_test.exs +++ b/test/pleroma/web/activity_pub/activity_pub_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do @@ -7,7 +7,6 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do    use Oban.Testing, repo: Pleroma.Repo    alias Pleroma.Activity -  alias Pleroma.Config    alias Pleroma.Delivery    alias Pleroma.Instances    alias Pleroma.Object @@ -46,7 +45,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "with the relay disabled, it returns 404", %{conn: conn} do -      Config.put([:instance, :allow_relay], false) +      clear_config([:instance, :allow_relay], false)        conn        |> get(activity_pub_path(conn, :relay)) @@ -54,7 +53,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "on non-federating instance, it returns 404", %{conn: conn} do -      Config.put([:instance, :federating], false) +      clear_config([:instance, :federating], false)        user = insert(:user)        conn @@ -75,7 +74,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "on non-federating instance, it returns 404", %{conn: conn} do -      Config.put([:instance, :federating], false) +      clear_config([:instance, :federating], false)        user = insert(:user)        conn @@ -219,7 +218,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert Pleroma.Web.ActivityPub.Visibility.is_local_public?(post) -      object = Object.normalize(post, false) +      object = Object.normalize(post, fetch: false)        uuid = String.split(object.data["id"], "/") |> List.last()        conn = @@ -230,6 +229,24 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert json_response(conn, 404)      end +    test "returns local-only objects when authenticated", %{conn: conn} do +      user = insert(:user) +      {:ok, post} = CommonAPI.post(user, %{status: "test", visibility: "local"}) + +      assert Pleroma.Web.ActivityPub.Visibility.is_local_public?(post) + +      object = Object.normalize(post, fetch: false) +      uuid = String.split(object.data["id"], "/") |> List.last() + +      assert response = +               conn +               |> assign(:user, user) +               |> put_req_header("accept", "application/activity+json") +               |> get("/objects/#{uuid}") + +      assert json_response(response, 200) == ObjectView.render("object.json", %{object: object}) +    end +      test "it returns a json representation of the object with accept application/json", %{        conn: conn      } do @@ -286,6 +303,28 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert json_response(conn, 404)      end +    test "returns visible non-public messages when authenticated", %{conn: conn} do +      note = insert(:direct_note) +      uuid = String.split(note.data["id"], "/") |> List.last() +      user = User.get_by_ap_id(note.data["actor"]) +      marisa = insert(:user) + +      assert conn +             |> assign(:user, marisa) +             |> put_req_header("accept", "application/activity+json") +             |> get("/objects/#{uuid}") +             |> json_response(404) + +      assert response = +               conn +               |> assign(:user, user) +               |> put_req_header("accept", "application/activity+json") +               |> get("/objects/#{uuid}") +               |> json_response(200) + +      assert response == ObjectView.render("object.json", %{object: note}) +    end +      test "it returns 404 for tombstone objects", %{conn: conn} do        tombstone = insert(:tombstone)        uuid = String.split(tombstone.data["id"], "/") |> List.last() @@ -359,6 +398,23 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert json_response(conn, 404)      end +    test "returns local-only activities when authenticated", %{conn: conn} do +      user = insert(:user) +      {:ok, post} = CommonAPI.post(user, %{status: "test", visibility: "local"}) + +      assert Pleroma.Web.ActivityPub.Visibility.is_local_public?(post) + +      uuid = String.split(post.data["id"], "/") |> List.last() + +      assert response = +               conn +               |> assign(:user, user) +               |> put_req_header("accept", "application/activity+json") +               |> get("/activities/#{uuid}") + +      assert json_response(response, 200) == ObjectView.render("object.json", %{object: post}) +    end +      test "it returns a json representation of the activity", %{conn: conn} do        activity = insert(:note_activity)        uuid = String.split(activity.data["id"], "/") |> List.last() @@ -383,6 +439,28 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert json_response(conn, 404)      end +    test "returns visible non-public messages when authenticated", %{conn: conn} do +      note = insert(:direct_note_activity) +      uuid = String.split(note.data["id"], "/") |> List.last() +      user = User.get_by_ap_id(note.data["actor"]) +      marisa = insert(:user) + +      assert conn +             |> assign(:user, marisa) +             |> put_req_header("accept", "application/activity+json") +             |> get("/activities/#{uuid}") +             |> json_response(404) + +      assert response = +               conn +               |> assign(:user, user) +               |> put_req_header("accept", "application/activity+json") +               |> get("/activities/#{uuid}") +               |> json_response(200) + +      assert response == ObjectView.render("object.json", %{object: note}) +    end +      test "it caches a response", %{conn: conn} do        activity = insert(:note_activity)        uuid = String.split(activity.data["id"], "/") |> List.last() @@ -493,7 +571,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "accept follow activity", %{conn: conn} do -      Pleroma.Config.put([:instance, :federating], true) +      clear_config([:instance, :federating], true)        relay = Relay.get_actor()        assert {:ok, %Activity{} = activity} = Relay.follow("https://relay.mastodon.host/actor") @@ -539,7 +617,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        conn = put_req_header(conn, "content-type", "application/activity+json") -      Config.put([:instance, :federating], false) +      clear_config([:instance, :federating], false)        conn        |> post("/inbox", data) @@ -549,7 +627,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        |> post("/inbox", non_create_data)        |> json_response(403) -      Config.put([:instance, :federating], true) +      clear_config([:instance, :federating], true)        ret_conn = post(conn, "/inbox", data)        assert "ok" == json_response(ret_conn, 200) @@ -558,6 +636,186 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        |> post("/inbox", non_create_data)        |> json_response(400)      end + +    test "accepts Add/Remove activities", %{conn: conn} do +      object_id = "c61d6733-e256-4fe1-ab13-1e369789423f" + +      status = +        File.read!("test/fixtures/statuses/note.json") +        |> String.replace("{{nickname}}", "lain") +        |> String.replace("{{object_id}}", object_id) + +      object_url = "https://example.com/objects/#{object_id}" + +      user = +        File.read!("test/fixtures/users_mock/user.json") +        |> String.replace("{{nickname}}", "lain") + +      actor = "https://example.com/users/lain" + +      Tesla.Mock.mock(fn +        %{ +          method: :get, +          url: ^object_url +        } -> +          %Tesla.Env{ +            status: 200, +            body: status, +            headers: [{"content-type", "application/activity+json"}] +          } + +        %{ +          method: :get, +          url: ^actor +        } -> +          %Tesla.Env{ +            status: 200, +            body: user, +            headers: [{"content-type", "application/activity+json"}] +          } + +        %{method: :get, url: "https://example.com/users/lain/collections/featured"} -> +          %Tesla.Env{ +            status: 200, +            body: +              "test/fixtures/users_mock/masto_featured.json" +              |> File.read!() +              |> String.replace("{{domain}}", "example.com") +              |> String.replace("{{nickname}}", "lain"), +            headers: [{"content-type", "application/activity+json"}] +          } +      end) + +      data = %{ +        "id" => "https://example.com/objects/d61d6733-e256-4fe1-ab13-1e369789423f", +        "actor" => actor, +        "object" => object_url, +        "target" => "https://example.com/users/lain/collections/featured", +        "type" => "Add", +        "to" => [Pleroma.Constants.as_public()] +      } + +      assert "ok" == +               conn +               |> assign(:valid_signature, true) +               |> put_req_header("content-type", "application/activity+json") +               |> post("/inbox", data) +               |> json_response(200) + +      ObanHelpers.perform(all_enqueued(worker: ReceiverWorker)) +      assert Activity.get_by_ap_id(data["id"]) +      user = User.get_cached_by_ap_id(data["actor"]) +      assert user.pinned_objects[data["object"]] + +      data = %{ +        "id" => "https://example.com/objects/d61d6733-e256-4fe1-ab13-1e369789423d", +        "actor" => actor, +        "object" => object_url, +        "target" => "https://example.com/users/lain/collections/featured", +        "type" => "Remove", +        "to" => [Pleroma.Constants.as_public()] +      } + +      assert "ok" == +               conn +               |> assign(:valid_signature, true) +               |> put_req_header("content-type", "application/activity+json") +               |> post("/inbox", data) +               |> json_response(200) + +      ObanHelpers.perform(all_enqueued(worker: ReceiverWorker)) +      user = refresh_record(user) +      refute user.pinned_objects[data["object"]] +    end + +    test "mastodon pin/unpin", %{conn: conn} do +      status_id = "105786274556060421" + +      status = +        File.read!("test/fixtures/statuses/masto-note.json") +        |> String.replace("{{nickname}}", "lain") +        |> String.replace("{{status_id}}", status_id) + +      status_url = "https://example.com/users/lain/statuses/#{status_id}" + +      user = +        File.read!("test/fixtures/users_mock/user.json") +        |> String.replace("{{nickname}}", "lain") + +      actor = "https://example.com/users/lain" + +      Tesla.Mock.mock(fn +        %{ +          method: :get, +          url: ^status_url +        } -> +          %Tesla.Env{ +            status: 200, +            body: status, +            headers: [{"content-type", "application/activity+json"}] +          } + +        %{ +          method: :get, +          url: ^actor +        } -> +          %Tesla.Env{ +            status: 200, +            body: user, +            headers: [{"content-type", "application/activity+json"}] +          } + +        %{method: :get, url: "https://example.com/users/lain/collections/featured"} -> +          %Tesla.Env{ +            status: 200, +            body: +              "test/fixtures/users_mock/masto_featured.json" +              |> File.read!() +              |> String.replace("{{domain}}", "example.com") +              |> String.replace("{{nickname}}", "lain"), +            headers: [{"content-type", "application/activity+json"}] +          } +      end) + +      data = %{ +        "@context" => "https://www.w3.org/ns/activitystreams", +        "actor" => actor, +        "object" => status_url, +        "target" => "https://example.com/users/lain/collections/featured", +        "type" => "Add" +      } + +      assert "ok" == +               conn +               |> assign(:valid_signature, true) +               |> put_req_header("content-type", "application/activity+json") +               |> post("/inbox", data) +               |> json_response(200) + +      ObanHelpers.perform(all_enqueued(worker: ReceiverWorker)) +      assert Activity.get_by_object_ap_id_with_object(data["object"]) +      user = User.get_cached_by_ap_id(data["actor"]) +      assert user.pinned_objects[data["object"]] + +      data = %{ +        "actor" => actor, +        "object" => status_url, +        "target" => "https://example.com/users/lain/collections/featured", +        "type" => "Remove" +      } + +      assert "ok" == +               conn +               |> assign(:valid_signature, true) +               |> put_req_header("content-type", "application/activity+json") +               |> post("/inbox", data) +               |> json_response(200) + +      ObanHelpers.perform(all_enqueued(worker: ReceiverWorker)) +      assert Activity.get_by_object_ap_id_with_object(data["object"]) +      user = refresh_record(user) +      refute user.pinned_objects[data["object"]] +    end    end    describe "/users/:nickname/inbox" do @@ -712,7 +970,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it returns a note activity in a collection", %{conn: conn} do        note_activity = insert(:direct_note_activity) -      note_object = Object.normalize(note_activity) +      note_object = Object.normalize(note_activity, fetch: false)        user = User.get_cached_by_ap_id(hd(note_activity.data["to"]))        conn = @@ -999,7 +1257,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it returns a note activity in a collection", %{conn: conn} do        note_activity = insert(:note_activity) -      note_object = Object.normalize(note_activity) +      note_object = Object.normalize(note_activity, fetch: false)        user = User.get_cached_by_ap_id(note_activity.data["actor"])        conn = @@ -1023,6 +1281,31 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert response(conn, 200) =~ announce_activity.data["object"]      end + +    test "It returns poll Answers when authenticated", %{conn: conn} do +      poller = insert(:user) +      voter = insert(:user) + +      {:ok, activity} = +        CommonAPI.post(poller, %{ +          status: "suya...", +          poll: %{options: ["suya", "suya.", "suya.."], expires_in: 10} +        }) + +      assert question = Object.normalize(activity, fetch: false) + +      {:ok, [activity], _object} = CommonAPI.vote(voter, question, [1]) + +      assert outbox_get = +               conn +               |> assign(:user, voter) +               |> put_req_header("accept", "application/activity+json") +               |> get(voter.ap_id <> "/outbox?page=true") +               |> json_response(200) + +      assert [answer_outbox] = outbox_get["orderedItems"] +      assert answer_outbox["id"] == activity.data["id"] +    end    end    describe "POST /users/:nickname/outbox (C2S)" do @@ -1073,7 +1356,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert Activity.get_by_ap_id(result["id"])        assert result["object"] -      assert %Object{data: object} = Object.normalize(result["object"]) +      assert %Object{data: object} = Object.normalize(result["object"], fetch: false)        assert object["content"] == activity["object"]["content"]      end @@ -1109,7 +1392,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert Activity.get_by_ap_id(response["id"])        assert response["object"] -      assert %Object{data: response_object} = Object.normalize(response["object"]) +      assert %Object{data: response_object} = Object.normalize(response["object"], fetch: false)        assert response_object["sensitive"] == true        assert response_object["content"] == activity["object"]["content"] @@ -1137,7 +1420,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it erects a tombstone when receiving a delete activity", %{conn: conn} do        note_activity = insert(:note_activity) -      note_object = Object.normalize(note_activity) +      note_object = Object.normalize(note_activity, fetch: false)        user = User.get_cached_by_ap_id(note_activity.data["actor"])        data = %{ @@ -1162,7 +1445,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it rejects delete activity of object from other actor", %{conn: conn} do        note_activity = insert(:note_activity) -      note_object = Object.normalize(note_activity) +      note_object = Object.normalize(note_activity, fetch: false)        user = insert(:user)        data = %{ @@ -1183,7 +1466,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it increases like count when receiving a like action", %{conn: conn} do        note_activity = insert(:note_activity) -      note_object = Object.normalize(note_activity) +      note_object = Object.normalize(note_activity, fetch: false)        user = User.get_cached_by_ap_id(note_activity.data["actor"])        data = %{ @@ -1240,13 +1523,13 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert cirno_outbox["attributedTo"] == nil        assert cirno_outbox["actor"] == cirno.ap_id -      assert cirno_object = Object.normalize(cirno_outbox["object"]) +      assert cirno_object = Object.normalize(cirno_outbox["object"], fetch: false)        assert cirno_object.data["actor"] == cirno.ap_id        assert cirno_object.data["attributedTo"] == cirno.ap_id      end      test "Character limitation", %{conn: conn, activity: activity} do -      Pleroma.Config.put([:instance, :limit], 5) +      clear_config([:instance, :limit], 5)        user = insert(:user)        result = @@ -1275,7 +1558,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "on non-federating instance, it returns 404", %{conn: conn} do -      Config.put([:instance, :federating], false) +      clear_config([:instance, :federating], false)        user = insert(:user)        conn @@ -1296,7 +1579,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      end      test "on non-federating instance, it returns 404", %{conn: conn} do -      Config.put([:instance, :federating], false) +      clear_config([:instance, :federating], false)        user = insert(:user)        conn @@ -1503,7 +1786,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it tracks a signed object fetch", %{conn: conn} do        user = insert(:user, local: false)        activity = insert(:note_activity) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        object_path = String.trim_leading(object.data["id"], Pleroma.Web.Endpoint.url()) @@ -1519,7 +1802,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do      test "it tracks a signed activity fetch", %{conn: conn} do        user = insert(:user, local: false)        activity = insert(:note_activity) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        activity_path = String.trim_leading(activity.data["id"], Pleroma.Web.Endpoint.url()) @@ -1536,7 +1819,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        user = insert(:user, local: false)        other_user = insert(:user, local: false)        activity = insert(:note_activity) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        object_path = String.trim_leading(object.data["id"], Pleroma.Web.Endpoint.url()) @@ -1560,7 +1843,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        user = insert(:user, local: false)        other_user = insert(:user, local: false)        activity = insert(:note_activity) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        activity_path = String.trim_leading(activity.data["id"], Pleroma.Web.Endpoint.url()) @@ -1608,9 +1891,9 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        desc = "Description of the image"        image = %Plug.Upload{ -        content_type: "bad/content-type", +        content_type: "image/jpeg",          path: Path.absname("test/fixtures/image.jpg"), -        filename: "an_image.png" +        filename: "an_image.jpg"        }        object = @@ -1650,7 +1933,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        assert activity_response["actor"] == user.ap_id        assert %Object{data: %{"attachment" => [attachment]}} = -               Object.normalize(activity_response["object"]) +               Object.normalize(activity_response["object"], fetch: false)        assert attachment["type"] == "Document"        assert attachment["name"] == desc @@ -1669,4 +1952,29 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubControllerTest do        |> json_response(403)      end    end + +  test "pinned collection", %{conn: conn} do +    clear_config([:instance, :max_pinned_statuses], 2) +    user = insert(:user) +    objects = insert_list(2, :note, user: user) + +    Enum.reduce(objects, user, fn %{data: %{"id" => object_id}}, user -> +      {:ok, updated} = User.add_pinned_object_id(user, object_id) +      updated +    end) + +    %{nickname: nickname, featured_address: featured_address, pinned_objects: pinned_objects} = +      refresh_record(user) + +    %{"id" => ^featured_address, "orderedItems" => items} = +      conn +      |> get("/users/#{nickname}/collections/featured") +      |> json_response(200) + +    object_ids = Enum.map(items, & &1["id"]) + +    assert Enum.all?(pinned_objects, fn {obj_id, _} -> +             obj_id in object_ids +           end) +  end  end diff --git a/test/pleroma/web/activity_pub/activity_pub_test.exs b/test/pleroma/web/activity_pub/activity_pub_test.exs index 9eb7ae86b..64e12066e 100644 --- a/test/pleroma/web/activity_pub/activity_pub_test.exs +++ b/test/pleroma/web/activity_pub/activity_pub_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ActivityPubTest do @@ -190,37 +190,191 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        assert user.accepts_chat_messages      end + +    test "works for guppe actors" do +      user_id = "https://gup.pe/u/bernie2020" + +      Tesla.Mock.mock(fn +        %{method: :get, url: ^user_id} -> +          %Tesla.Env{ +            status: 200, +            body: File.read!("test/fixtures/guppe-actor.json"), +            headers: [{"content-type", "application/activity+json"}] +          } +      end) + +      {:ok, user} = ActivityPub.make_user_from_ap_id(user_id) + +      assert user.name == "Bernie2020 group" +      assert user.actor_type == "Group" +    end + +    test "works for bridgy actors" do +      user_id = "https://fed.brid.gy/jk.nipponalba.scot" + +      Tesla.Mock.mock(fn +        %{method: :get, url: ^user_id} -> +          %Tesla.Env{ +            status: 200, +            body: File.read!("test/fixtures/bridgy/actor.json"), +            headers: [{"content-type", "application/activity+json"}] +          } +      end) + +      {:ok, user} = ActivityPub.make_user_from_ap_id(user_id) + +      assert user.actor_type == "Person" + +      assert user.avatar == %{ +               "type" => "Image", +               "url" => [%{"href" => "https://jk.nipponalba.scot/images/profile.jpg"}] +             } + +      assert user.banner == %{ +               "type" => "Image", +               "url" => [%{"href" => "https://jk.nipponalba.scot/images/profile.jpg"}] +             } +    end + +    test "fetches user featured collection" do +      ap_id = "https://example.com/users/lain" + +      featured_url = "https://example.com/users/lain/collections/featured" + +      user_data = +        "test/fixtures/users_mock/user.json" +        |> File.read!() +        |> String.replace("{{nickname}}", "lain") +        |> Jason.decode!() +        |> Map.put("featured", featured_url) +        |> Jason.encode!() + +      object_id = Ecto.UUID.generate() + +      featured_data = +        "test/fixtures/mastodon/collections/featured.json" +        |> File.read!() +        |> String.replace("{{domain}}", "example.com") +        |> String.replace("{{nickname}}", "lain") +        |> String.replace("{{object_id}}", object_id) + +      object_url = "https://example.com/objects/#{object_id}" + +      object_data = +        "test/fixtures/statuses/note.json" +        |> File.read!() +        |> String.replace("{{object_id}}", object_id) +        |> String.replace("{{nickname}}", "lain") + +      Tesla.Mock.mock(fn +        %{ +          method: :get, +          url: ^ap_id +        } -> +          %Tesla.Env{ +            status: 200, +            body: user_data, +            headers: [{"content-type", "application/activity+json"}] +          } + +        %{ +          method: :get, +          url: ^featured_url +        } -> +          %Tesla.Env{ +            status: 200, +            body: featured_data, +            headers: [{"content-type", "application/activity+json"}] +          } +      end) + +      Tesla.Mock.mock_global(fn +        %{ +          method: :get, +          url: ^object_url +        } -> +          %Tesla.Env{ +            status: 200, +            body: object_data, +            headers: [{"content-type", "application/activity+json"}] +          } +      end) + +      {:ok, user} = ActivityPub.make_user_from_ap_id(ap_id) +      Process.sleep(50) + +      assert user.featured_address == featured_url +      assert Map.has_key?(user.pinned_objects, object_url) + +      in_db = Pleroma.User.get_by_ap_id(ap_id) +      assert in_db.featured_address == featured_url +      assert Map.has_key?(user.pinned_objects, object_url) + +      assert %{data: %{"id" => ^object_url}} = Object.get_by_ap_id(object_url) +    end    end    test "it fetches the appropriate tag-restricted posts" do      user = insert(:user) -    {:ok, status_one} = CommonAPI.post(user, %{status: ". #test"}) +    {:ok, status_one} = CommonAPI.post(user, %{status: ". #TEST"})      {:ok, status_two} = CommonAPI.post(user, %{status: ". #essais"}) -    {:ok, status_three} = CommonAPI.post(user, %{status: ". #test #reject"}) +    {:ok, status_three} = CommonAPI.post(user, %{status: ". #test #Reject"}) -    fetch_one = ActivityPub.fetch_activities([], %{type: "Create", tag: "test"}) +    {:ok, status_four} = CommonAPI.post(user, %{status: ". #Any1 #any2"}) +    {:ok, status_five} = CommonAPI.post(user, %{status: ". #Any2 #any1"}) -    fetch_two = ActivityPub.fetch_activities([], %{type: "Create", tag: ["test", "essais"]}) +    for hashtag_timeline_strategy <- [:enabled, :disabled] do +      clear_config([:features, :improved_hashtag_timeline], hashtag_timeline_strategy) -    fetch_three = -      ActivityPub.fetch_activities([], %{ -        type: "Create", -        tag: ["test", "essais"], -        tag_reject: ["reject"] -      }) +      fetch_one = ActivityPub.fetch_activities([], %{type: "Create", tag: "test"}) -    fetch_four = -      ActivityPub.fetch_activities([], %{ -        type: "Create", -        tag: ["test"], -        tag_all: ["test", "reject"] -      }) +      fetch_two = ActivityPub.fetch_activities([], %{type: "Create", tag: ["TEST", "essais"]}) + +      fetch_three = +        ActivityPub.fetch_activities([], %{ +          type: "Create", +          tag: ["test", "Essais"], +          tag_reject: ["reject"] +        }) -    assert fetch_one == [status_one, status_three] -    assert fetch_two == [status_one, status_two, status_three] -    assert fetch_three == [status_one, status_two] -    assert fetch_four == [status_three] +      fetch_four = +        ActivityPub.fetch_activities([], %{ +          type: "Create", +          tag: ["test"], +          tag_all: ["test", "REJECT"] +        }) + +      # Testing that deduplication (if needed) is done on DB (not Ecto) level; :limit is important +      fetch_five = +        ActivityPub.fetch_activities([], %{ +          type: "Create", +          tag: ["ANY1", "any2"], +          limit: 2 +        }) + +      fetch_six = +        ActivityPub.fetch_activities([], %{ +          type: "Create", +          tag: ["any1", "Any2"], +          tag_all: [], +          tag_reject: [] +        }) + +      # Regression test: passing empty lists as filter options shouldn't affect the results +      assert fetch_five == fetch_six + +      [fetch_one, fetch_two, fetch_three, fetch_four, fetch_five] = +        Enum.map([fetch_one, fetch_two, fetch_three, fetch_four, fetch_five], fn statuses -> +          Enum.map(statuses, fn s -> Repo.preload(s, object: :hashtags) end) +        end) + +      assert fetch_one == [status_one, status_three] +      assert fetch_two == [status_one, status_two, status_three] +      assert fetch_three == [status_one, status_two] +      assert fetch_four == [status_three] +      assert fetch_five == [status_four, status_five] +    end    end    describe "insertion" do @@ -321,7 +475,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        }        {:ok, %Activity{} = activity} = ActivityPub.insert(data) -      object = Pleroma.Object.normalize(activity) +      object = Pleroma.Object.normalize(activity, fetch: false)        assert is_binary(activity.data["context"])        assert is_binary(object.data["context"]) @@ -344,7 +498,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do        }        {:ok, %Activity{} = activity} = ActivityPub.insert(data) -      assert object = Object.normalize(activity) +      assert object = Object.normalize(activity, fetch: false)        assert is_binary(object.data["id"])      end    end @@ -678,7 +832,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do      {:ok, activity_two} = CommonAPI.post(blockee, %{status: "hey! @#{friend.nickname}"}) -    assert object = Pleroma.Object.normalize(activity_two) +    assert object = Pleroma.Object.normalize(activity_two, fetch: false)      data = %{        "actor" => friend.ap_id, @@ -1061,15 +1215,15 @@ defmodule Pleroma.Web.ActivityPub.ActivityPubTest do      test "it sets the default description depending on the configuration", %{test_file: file} do        clear_config([Pleroma.Upload, :default_description]) -      Pleroma.Config.put([Pleroma.Upload, :default_description], nil) +      clear_config([Pleroma.Upload, :default_description], nil)        {:ok, %Object{} = object} = ActivityPub.upload(file)        assert object.data["name"] == "" -      Pleroma.Config.put([Pleroma.Upload, :default_description], :filename) +      clear_config([Pleroma.Upload, :default_description], :filename)        {:ok, %Object{} = object} = ActivityPub.upload(file)        assert object.data["name"] == "an_image.jpg" -      Pleroma.Config.put([Pleroma.Upload, :default_description], "unnamed attachment") +      clear_config([Pleroma.Upload, :default_description], "unnamed attachment")        {:ok, %Object{} = object} = ActivityPub.upload(file)        assert object.data["name"] == "unnamed attachment"      end diff --git a/test/pleroma/web/activity_pub/mrf/activity_expiration_policy_test.exs b/test/pleroma/web/activity_pub/mrf/activity_expiration_policy_test.exs index e7370d4ef..47b07fdd9 100644 --- a/test/pleroma/web/activity_pub/mrf/activity_expiration_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/activity_expiration_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.ActivityExpirationPolicyTest do diff --git a/test/pleroma/web/activity_pub/mrf/anti_followbot_policy_test.exs b/test/pleroma/web/activity_pub/mrf/anti_followbot_policy_test.exs index 3c795f5ac..d5af3a9b6 100644 --- a/test/pleroma/web/activity_pub/mrf/anti_followbot_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/anti_followbot_policy_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.AntiFollowbotPolicyTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.ActivityPub.MRF.AntiFollowbotPolicy diff --git a/test/pleroma/web/activity_pub/mrf/anti_link_spam_policy_test.exs b/test/pleroma/web/activity_pub/mrf/anti_link_spam_policy_test.exs index 6867c9853..5b990451c 100644 --- a/test/pleroma/web/activity_pub/mrf/anti_link_spam_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/anti_link_spam_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.AntiLinkSpamPolicyTest do diff --git a/test/pleroma/web/activity_pub/mrf/ensure_re_prepended_test.exs b/test/pleroma/web/activity_pub/mrf/ensure_re_prepended_test.exs index 9a283f27d..89439b65f 100644 --- a/test/pleroma/web/activity_pub/mrf/ensure_re_prepended_test.exs +++ b/test/pleroma/web/activity_pub/mrf/ensure_re_prepended_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.EnsureRePrependedTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.Object diff --git a/test/pleroma/web/activity_pub/mrf/follow_bot_policy_test.exs b/test/pleroma/web/activity_pub/mrf/follow_bot_policy_test.exs new file mode 100644 index 000000000..a61562558 --- /dev/null +++ b/test/pleroma/web/activity_pub/mrf/follow_bot_policy_test.exs @@ -0,0 +1,126 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ActivityPub.MRF.FollowBotPolicyTest do +  use Pleroma.DataCase, async: true + +  alias Pleroma.User +  alias Pleroma.Web.ActivityPub.MRF.FollowBotPolicy + +  import Pleroma.Factory + +  describe "FollowBotPolicy" do +    test "follows remote users" do +      bot = insert(:user, actor_type: "Service") +      remote_user = insert(:user, local: false) +      clear_config([:mrf_follow_bot, :follower_nickname], bot.nickname) + +      message = %{ +        "@context" => "https://www.w3.org/ns/activitystreams", +        "to" => [remote_user.follower_address], +        "cc" => ["https://www.w3.org/ns/activitystreams#Public"], +        "type" => "Create", +        "object" => %{ +          "content" => "Test post", +          "type" => "Note", +          "attributedTo" => remote_user.ap_id, +          "inReplyTo" => nil +        }, +        "actor" => remote_user.ap_id +      } + +      refute User.following?(bot, remote_user) + +      assert User.get_follow_requests(remote_user) |> length == 0 + +      FollowBotPolicy.filter(message) + +      assert User.get_follow_requests(remote_user) |> length == 1 +    end + +    test "does not follow users with #nobot in bio" do +      bot = insert(:user, actor_type: "Service") +      remote_user = insert(:user, %{local: false, bio: "go away bots! #nobot"}) +      clear_config([:mrf_follow_bot, :follower_nickname], bot.nickname) + +      message = %{ +        "@context" => "https://www.w3.org/ns/activitystreams", +        "to" => [remote_user.follower_address], +        "cc" => ["https://www.w3.org/ns/activitystreams#Public"], +        "type" => "Create", +        "object" => %{ +          "content" => "I don't like follow bots", +          "type" => "Note", +          "attributedTo" => remote_user.ap_id, +          "inReplyTo" => nil +        }, +        "actor" => remote_user.ap_id +      } + +      refute User.following?(bot, remote_user) + +      assert User.get_follow_requests(remote_user) |> length == 0 + +      FollowBotPolicy.filter(message) + +      assert User.get_follow_requests(remote_user) |> length == 0 +    end + +    test "does not follow local users" do +      bot = insert(:user, actor_type: "Service") +      local_user = insert(:user, local: true) +      clear_config([:mrf_follow_bot, :follower_nickname], bot.nickname) + +      message = %{ +        "@context" => "https://www.w3.org/ns/activitystreams", +        "to" => [local_user.follower_address], +        "cc" => ["https://www.w3.org/ns/activitystreams#Public"], +        "type" => "Create", +        "object" => %{ +          "content" => "Hi I'm a local user", +          "type" => "Note", +          "attributedTo" => local_user.ap_id, +          "inReplyTo" => nil +        }, +        "actor" => local_user.ap_id +      } + +      refute User.following?(bot, local_user) + +      assert User.get_follow_requests(local_user) |> length == 0 + +      FollowBotPolicy.filter(message) + +      assert User.get_follow_requests(local_user) |> length == 0 +    end + +    test "does not follow users requiring follower approval" do +      bot = insert(:user, actor_type: "Service") +      remote_user = insert(:user, %{local: false, is_locked: true}) +      clear_config([:mrf_follow_bot, :follower_nickname], bot.nickname) + +      message = %{ +        "@context" => "https://www.w3.org/ns/activitystreams", +        "to" => [remote_user.follower_address], +        "cc" => ["https://www.w3.org/ns/activitystreams#Public"], +        "type" => "Create", +        "object" => %{ +          "content" => "I don't like randos following me", +          "type" => "Note", +          "attributedTo" => remote_user.ap_id, +          "inReplyTo" => nil +        }, +        "actor" => remote_user.ap_id +      } + +      refute User.following?(bot, remote_user) + +      assert User.get_follow_requests(remote_user) |> length == 0 + +      FollowBotPolicy.filter(message) + +      assert User.get_follow_requests(remote_user) |> length == 0 +    end +  end +end diff --git a/test/pleroma/web/activity_pub/mrf/force_bot_unlisted_policy_test.exs b/test/pleroma/web/activity_pub/mrf/force_bot_unlisted_policy_test.exs index 86dd9ddae..e3325d144 100644 --- a/test/pleroma/web/activity_pub/mrf/force_bot_unlisted_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/force_bot_unlisted_policy_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.ForceBotUnlistedPolicyTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.ActivityPub.MRF.ForceBotUnlistedPolicy diff --git a/test/pleroma/web/activity_pub/mrf/hashtag_policy_test.exs b/test/pleroma/web/activity_pub/mrf/hashtag_policy_test.exs new file mode 100644 index 000000000..13415bb79 --- /dev/null +++ b/test/pleroma/web/activity_pub/mrf/hashtag_policy_test.exs @@ -0,0 +1,31 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ActivityPub.MRF.HashtagPolicyTest do +  use Oban.Testing, repo: Pleroma.Repo +  use Pleroma.DataCase + +  alias Pleroma.Web.ActivityPub.Transmogrifier +  alias Pleroma.Web.CommonAPI + +  import Pleroma.Factory + +  test "it sets the sensitive property with relevant hashtags" do +    user = insert(:user) + +    {:ok, activity} = CommonAPI.post(user, %{status: "#nsfw hey"}) +    {:ok, modified} = Transmogrifier.prepare_outgoing(activity.data) + +    assert modified["object"]["sensitive"] +  end + +  test "it doesn't sets the sensitive property with irrelevant hashtags" do +    user = insert(:user) + +    {:ok, activity} = CommonAPI.post(user, %{status: "#cofe hey"}) +    {:ok, modified} = Transmogrifier.prepare_outgoing(activity.data) + +    refute modified["object"]["sensitive"] +  end +end diff --git a/test/pleroma/web/activity_pub/mrf/hellthread_policy_test.exs b/test/pleroma/web/activity_pub/mrf/hellthread_policy_test.exs index 26f5bcdaa..439672479 100644 --- a/test/pleroma/web/activity_pub/mrf/hellthread_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/hellthread_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicyTest do @@ -34,7 +34,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicyTest do    setup do: clear_config(:mrf_hellthread)    test "doesn't die on chat messages" do -    Pleroma.Config.put([:mrf_hellthread], %{delist_threshold: 2, reject_threshold: 0}) +    clear_config([:mrf_hellthread], %{delist_threshold: 2, reject_threshold: 0})      user = insert(:user)      other_user = insert(:user) @@ -48,7 +48,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicyTest do      test "rejects the message if the recipient count is above reject_threshold", %{        message: message      } do -      Pleroma.Config.put([:mrf_hellthread], %{delist_threshold: 0, reject_threshold: 2}) +      clear_config([:mrf_hellthread], %{delist_threshold: 0, reject_threshold: 2})        assert {:reject, "[HellthreadPolicy] 3 recipients is over the limit of 2"} ==                 filter(message) @@ -57,7 +57,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicyTest do      test "does not reject the message if the recipient count is below reject_threshold", %{        message: message      } do -      Pleroma.Config.put([:mrf_hellthread], %{delist_threshold: 0, reject_threshold: 3}) +      clear_config([:mrf_hellthread], %{delist_threshold: 0, reject_threshold: 3})        assert {:ok, ^message} = filter(message)      end @@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicyTest do        user: user,        message: message      } do -      Pleroma.Config.put([:mrf_hellthread], %{delist_threshold: 2, reject_threshold: 0}) +      clear_config([:mrf_hellthread], %{delist_threshold: 2, reject_threshold: 0})        {:ok, message} = filter(message)        assert user.follower_address in message["to"] @@ -78,14 +78,14 @@ defmodule Pleroma.Web.ActivityPub.MRF.HellthreadPolicyTest do      test "does not delist the message if the recipient count is below delist_threshold", %{        message: message      } do -      Pleroma.Config.put([:mrf_hellthread], %{delist_threshold: 4, reject_threshold: 0}) +      clear_config([:mrf_hellthread], %{delist_threshold: 4, reject_threshold: 0})        assert {:ok, ^message} = filter(message)      end    end    test "excludes follower collection and public URI from threshold count", %{message: message} do -    Pleroma.Config.put([:mrf_hellthread], %{delist_threshold: 0, reject_threshold: 3}) +    clear_config([:mrf_hellthread], %{delist_threshold: 0, reject_threshold: 3})      assert {:ok, ^message} = filter(message)    end diff --git a/test/pleroma/web/activity_pub/mrf/keyword_policy_test.exs b/test/pleroma/web/activity_pub/mrf/keyword_policy_test.exs index b3d0f3d90..8af4c5efa 100644 --- a/test/pleroma/web/activity_pub/mrf/keyword_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/keyword_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do @@ -10,12 +10,12 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do    setup do: clear_config(:mrf_keyword)    setup do -    Pleroma.Config.put([:mrf_keyword], %{reject: [], federated_timeline_removal: [], replace: []}) +    clear_config([:mrf_keyword], %{reject: [], federated_timeline_removal: [], replace: []})    end    describe "rejecting based on keywords" do      test "rejects if string matches in content" do -      Pleroma.Config.put([:mrf_keyword, :reject], ["pun"]) +      clear_config([:mrf_keyword, :reject], ["pun"])        message = %{          "type" => "Create", @@ -30,7 +30,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "rejects if string matches in summary" do -      Pleroma.Config.put([:mrf_keyword, :reject], ["pun"]) +      clear_config([:mrf_keyword, :reject], ["pun"])        message = %{          "type" => "Create", @@ -45,7 +45,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "rejects if regex matches in content" do -      Pleroma.Config.put([:mrf_keyword, :reject], [~r/comp[lL][aA][iI][nN]er/]) +      clear_config([:mrf_keyword, :reject], [~r/comp[lL][aA][iI][nN]er/])        assert true ==                 Enum.all?(["complainer", "compLainer", "compLAiNer", "compLAINer"], fn content -> @@ -63,7 +63,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "rejects if regex matches in summary" do -      Pleroma.Config.put([:mrf_keyword, :reject], [~r/comp[lL][aA][iI][nN]er/]) +      clear_config([:mrf_keyword, :reject], [~r/comp[lL][aA][iI][nN]er/])        assert true ==                 Enum.all?(["complainer", "compLainer", "compLAiNer", "compLAINer"], fn content -> @@ -83,7 +83,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do    describe "delisting from ftl based on keywords" do      test "delists if string matches in content" do -      Pleroma.Config.put([:mrf_keyword, :federated_timeline_removal], ["pun"]) +      clear_config([:mrf_keyword, :federated_timeline_removal], ["pun"])        message = %{          "to" => ["https://www.w3.org/ns/activitystreams#Public"], @@ -100,7 +100,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "delists if string matches in summary" do -      Pleroma.Config.put([:mrf_keyword, :federated_timeline_removal], ["pun"]) +      clear_config([:mrf_keyword, :federated_timeline_removal], ["pun"])        message = %{          "to" => ["https://www.w3.org/ns/activitystreams#Public"], @@ -117,7 +117,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "delists if regex matches in content" do -      Pleroma.Config.put([:mrf_keyword, :federated_timeline_removal], [~r/comp[lL][aA][iI][nN]er/]) +      clear_config([:mrf_keyword, :federated_timeline_removal], [~r/comp[lL][aA][iI][nN]er/])        assert true ==                 Enum.all?(["complainer", "compLainer", "compLAiNer", "compLAINer"], fn content -> @@ -138,7 +138,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "delists if regex matches in summary" do -      Pleroma.Config.put([:mrf_keyword, :federated_timeline_removal], [~r/comp[lL][aA][iI][nN]er/]) +      clear_config([:mrf_keyword, :federated_timeline_removal], [~r/comp[lL][aA][iI][nN]er/])        assert true ==                 Enum.all?(["complainer", "compLainer", "compLAiNer", "compLAINer"], fn content -> @@ -161,7 +161,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do    describe "replacing keywords" do      test "replaces keyword if string matches in content" do -      Pleroma.Config.put([:mrf_keyword, :replace], [{"opensource", "free software"}]) +      clear_config([:mrf_keyword, :replace], [{"opensource", "free software"}])        message = %{          "type" => "Create", @@ -174,7 +174,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "replaces keyword if string matches in summary" do -      Pleroma.Config.put([:mrf_keyword, :replace], [{"opensource", "free software"}]) +      clear_config([:mrf_keyword, :replace], [{"opensource", "free software"}])        message = %{          "type" => "Create", @@ -187,7 +187,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "replaces keyword if regex matches in content" do -      Pleroma.Config.put([:mrf_keyword, :replace], [ +      clear_config([:mrf_keyword, :replace], [          {~r/open(-|\s)?source\s?(software)?/, "free software"}        ]) @@ -205,7 +205,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicyTest do      end      test "replaces keyword if regex matches in summary" do -      Pleroma.Config.put([:mrf_keyword, :replace], [ +      clear_config([:mrf_keyword, :replace], [          {~r/open(-|\s)?source\s?(software)?/, "free software"}        ]) diff --git a/test/pleroma/web/activity_pub/mrf/media_proxy_warming_policy_test.exs b/test/pleroma/web/activity_pub/mrf/media_proxy_warming_policy_test.exs index 84362ce78..96e715d0d 100644 --- a/test/pleroma/web/activity_pub/mrf/media_proxy_warming_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/media_proxy_warming_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicyTest do diff --git a/test/pleroma/web/activity_pub/mrf/mention_policy_test.exs b/test/pleroma/web/activity_pub/mrf/mention_policy_test.exs index 220309cc9..80ddcacbe 100644 --- a/test/pleroma/web/activity_pub/mrf/mention_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/mention_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do @@ -23,7 +23,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do    describe "allow" do      test "empty" do -      Pleroma.Config.put([:mrf_mention], %{actors: ["https://example.com/blocked"]}) +      clear_config([:mrf_mention], %{actors: ["https://example.com/blocked"]})        message = %{          "type" => "Create" @@ -33,7 +33,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do      end      test "to" do -      Pleroma.Config.put([:mrf_mention], %{actors: ["https://example.com/blocked"]}) +      clear_config([:mrf_mention], %{actors: ["https://example.com/blocked"]})        message = %{          "type" => "Create", @@ -44,7 +44,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do      end      test "cc" do -      Pleroma.Config.put([:mrf_mention], %{actors: ["https://example.com/blocked"]}) +      clear_config([:mrf_mention], %{actors: ["https://example.com/blocked"]})        message = %{          "type" => "Create", @@ -55,7 +55,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do      end      test "both" do -      Pleroma.Config.put([:mrf_mention], %{actors: ["https://example.com/blocked"]}) +      clear_config([:mrf_mention], %{actors: ["https://example.com/blocked"]})        message = %{          "type" => "Create", @@ -69,7 +69,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do    describe "deny" do      test "to" do -      Pleroma.Config.put([:mrf_mention], %{actors: ["https://example.com/blocked"]}) +      clear_config([:mrf_mention], %{actors: ["https://example.com/blocked"]})        message = %{          "type" => "Create", @@ -81,7 +81,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.MentionPolicyTest do      end      test "cc" do -      Pleroma.Config.put([:mrf_mention], %{actors: ["https://example.com/blocked"]}) +      clear_config([:mrf_mention], %{actors: ["https://example.com/blocked"]})        message = %{          "type" => "Create", diff --git a/test/pleroma/web/activity_pub/mrf/no_empty_policy_test.exs b/test/pleroma/web/activity_pub/mrf/no_empty_policy_test.exs new file mode 100644 index 000000000..fbcf68414 --- /dev/null +++ b/test/pleroma/web/activity_pub/mrf/no_empty_policy_test.exs @@ -0,0 +1,154 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ActivityPub.MRF.NoEmptyPolicyTest do +  use Pleroma.DataCase +  alias Pleroma.Web.ActivityPub.MRF.NoEmptyPolicy + +  setup_all do: clear_config([:mrf, :policies], [Pleroma.Web.ActivityPub.MRF.NoEmptyPolicy]) + +  test "Notes with content are exempt" do +    message = %{ +      "actor" => "http://localhost:4001/users/testuser", +      "cc" => ["http://localhost:4001/users/testuser/followers"], +      "object" => %{ +        "actor" => "http://localhost:4001/users/testuser", +        "attachment" => [], +        "cc" => ["http://localhost:4001/users/testuser/followers"], +        "source" => "this is a test post", +        "to" => ["https://www.w3.org/ns/activitystreams#Public"], +        "type" => "Note" +      }, +      "to" => ["https://www.w3.org/ns/activitystreams#Public"], +      "type" => "Create" +    } + +    assert NoEmptyPolicy.filter(message) == {:ok, message} +  end + +  test "Polls are exempt" do +    message = %{ +      "actor" => "http://localhost:4001/users/testuser", +      "cc" => ["http://localhost:4001/users/testuser/followers"], +      "object" => %{ +        "actor" => "http://localhost:4001/users/testuser", +        "attachment" => [], +        "cc" => ["http://localhost:4001/users/testuser/followers"], +        "oneOf" => [ +          %{ +            "name" => "chocolate", +            "replies" => %{"totalItems" => 0, "type" => "Collection"}, +            "type" => "Note" +          }, +          %{ +            "name" => "vanilla", +            "replies" => %{"totalItems" => 0, "type" => "Collection"}, +            "type" => "Note" +          } +        ], +        "source" => "@user2", +        "to" => [ +          "https://www.w3.org/ns/activitystreams#Public", +          "http://localhost:4001/users/user2" +        ], +        "type" => "Question" +      }, +      "to" => [ +        "https://www.w3.org/ns/activitystreams#Public", +        "http://localhost:4001/users/user2" +      ], +      "type" => "Create" +    } + +    assert NoEmptyPolicy.filter(message) == {:ok, message} +  end + +  test "Notes with attachments are exempt" do +    message = %{ +      "actor" => "http://localhost:4001/users/testuser", +      "cc" => ["http://localhost:4001/users/testuser/followers"], +      "object" => %{ +        "actor" => "http://localhost:4001/users/testuser", +        "attachment" => [ +          %{ +            "actor" => "http://localhost:4001/users/testuser", +            "mediaType" => "image/png", +            "name" => "", +            "type" => "Document", +            "url" => [ +              %{ +                "href" => +                  "http://localhost:4001/media/68ba231cf12e1382ce458f1979969f8ed5cc07ba198a02e653464abaf39bdb90.png", +                "mediaType" => "image/png", +                "type" => "Link" +              } +            ] +          } +        ], +        "cc" => ["http://localhost:4001/users/testuser/followers"], +        "source" => "@user2", +        "to" => [ +          "https://www.w3.org/ns/activitystreams#Public", +          "http://localhost:4001/users/user2" +        ], +        "type" => "Note" +      }, +      "to" => [ +        "https://www.w3.org/ns/activitystreams#Public", +        "http://localhost:4001/users/user2" +      ], +      "type" => "Create" +    } + +    assert NoEmptyPolicy.filter(message) == {:ok, message} +  end + +  test "Notes with only mentions are denied" do +    message = %{ +      "actor" => "http://localhost:4001/users/testuser", +      "cc" => ["http://localhost:4001/users/testuser/followers"], +      "object" => %{ +        "actor" => "http://localhost:4001/users/testuser", +        "attachment" => [], +        "cc" => ["http://localhost:4001/users/testuser/followers"], +        "source" => "@user2", +        "to" => [ +          "https://www.w3.org/ns/activitystreams#Public", +          "http://localhost:4001/users/user2" +        ], +        "type" => "Note" +      }, +      "to" => [ +        "https://www.w3.org/ns/activitystreams#Public", +        "http://localhost:4001/users/user2" +      ], +      "type" => "Create" +    } + +    assert NoEmptyPolicy.filter(message) == {:reject, "[NoEmptyPolicy]"} +  end + +  test "Notes with no content are denied" do +    message = %{ +      "actor" => "http://localhost:4001/users/testuser", +      "cc" => ["http://localhost:4001/users/testuser/followers"], +      "object" => %{ +        "actor" => "http://localhost:4001/users/testuser", +        "attachment" => [], +        "cc" => ["http://localhost:4001/users/testuser/followers"], +        "source" => "", +        "to" => [ +          "https://www.w3.org/ns/activitystreams#Public" +        ], +        "type" => "Note" +      }, +      "to" => [ +        "https://www.w3.org/ns/activitystreams#Public" +      ], +      "type" => "Create" +    } + +    assert NoEmptyPolicy.filter(message) == {:reject, "[NoEmptyPolicy]"} +  end +end diff --git a/test/pleroma/web/activity_pub/mrf/no_placeholder_text_policy_test.exs b/test/pleroma/web/activity_pub/mrf/no_placeholder_text_policy_test.exs index 64ea61dd4..81a6e0f50 100644 --- a/test/pleroma/web/activity_pub/mrf/no_placeholder_text_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/no_placeholder_text_policy_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.NoPlaceholderTextPolicyTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.MRF.NoPlaceholderTextPolicy    test "it clears content object" do diff --git a/test/pleroma/web/activity_pub/mrf/normalize_markup_test.exs b/test/pleroma/web/activity_pub/mrf/normalize_markup_test.exs index 9b39c45bd..edc330b6c 100644 --- a/test/pleroma/web/activity_pub/mrf/normalize_markup_test.exs +++ b/test/pleroma/web/activity_pub/mrf/normalize_markup_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.NormalizeMarkupTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.MRF.NormalizeMarkup    @html_sample """ diff --git a/test/pleroma/web/activity_pub/mrf/object_age_policy_test.exs b/test/pleroma/web/activity_pub/mrf/object_age_policy_test.exs index e8317b2af..137aafd39 100644 --- a/test/pleroma/web/activity_pub/mrf/object_age_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/object_age_policy_test.exs @@ -1,10 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.User    alias Pleroma.Web.ActivityPub.MRF.ObjectAgePolicy    alias Pleroma.Web.ActivityPub.Visibility @@ -39,7 +38,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do    describe "with reject action" do      test "works with objects with empty to or cc fields" do -      Config.put([:mrf_object_age, :actions], [:reject]) +      clear_config([:mrf_object_age, :actions], [:reject])        data =          get_old_message() @@ -50,7 +49,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do      end      test "it rejects an old post" do -      Config.put([:mrf_object_age, :actions], [:reject]) +      clear_config([:mrf_object_age, :actions], [:reject])        data = get_old_message() @@ -58,7 +57,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do      end      test "it allows a new post" do -      Config.put([:mrf_object_age, :actions], [:reject]) +      clear_config([:mrf_object_age, :actions], [:reject])        data = get_new_message() @@ -68,7 +67,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do    describe "with delist action" do      test "works with objects with empty to or cc fields" do -      Config.put([:mrf_object_age, :actions], [:delist]) +      clear_config([:mrf_object_age, :actions], [:delist])        data =          get_old_message() @@ -83,7 +82,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do      end      test "it delists an old post" do -      Config.put([:mrf_object_age, :actions], [:delist]) +      clear_config([:mrf_object_age, :actions], [:delist])        data = get_old_message() @@ -95,7 +94,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do      end      test "it allows a new post" do -      Config.put([:mrf_object_age, :actions], [:delist]) +      clear_config([:mrf_object_age, :actions], [:delist])        data = get_new_message() @@ -107,7 +106,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do    describe "with strip_followers action" do      test "works with objects with empty to or cc fields" do -      Config.put([:mrf_object_age, :actions], [:strip_followers]) +      clear_config([:mrf_object_age, :actions], [:strip_followers])        data =          get_old_message() @@ -123,7 +122,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do      end      test "it strips followers collections from an old post" do -      Config.put([:mrf_object_age, :actions], [:strip_followers]) +      clear_config([:mrf_object_age, :actions], [:strip_followers])        data = get_old_message() @@ -136,7 +135,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.ObjectAgePolicyTest do      end      test "it allows a new post" do -      Config.put([:mrf_object_age, :actions], [:strip_followers]) +      clear_config([:mrf_object_age, :actions], [:strip_followers])        data = get_new_message() diff --git a/test/pleroma/web/activity_pub/mrf/reject_non_public_test.exs b/test/pleroma/web/activity_pub/mrf/reject_non_public_test.exs index e08eb3ba6..63c68d798 100644 --- a/test/pleroma/web/activity_pub/mrf/reject_non_public_test.exs +++ b/test/pleroma/web/activity_pub/mrf/reject_non_public_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublicTest do @@ -49,7 +49,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublicTest do          "type" => "Create"        } -      Pleroma.Config.put([:mrf_rejectnonpublic, :allow_followersonly], true) +      clear_config([:mrf_rejectnonpublic, :allow_followersonly], true)        assert {:ok, _message} = RejectNonPublic.filter(message)      end @@ -63,7 +63,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublicTest do          "type" => "Create"        } -      Pleroma.Config.put([:mrf_rejectnonpublic, :allow_followersonly], false) +      clear_config([:mrf_rejectnonpublic, :allow_followersonly], false)        assert {:reject, _} = RejectNonPublic.filter(message)      end    end @@ -79,7 +79,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublicTest do          "type" => "Create"        } -      Pleroma.Config.put([:mrf_rejectnonpublic, :allow_direct], true) +      clear_config([:mrf_rejectnonpublic, :allow_direct], true)        assert {:ok, _message} = RejectNonPublic.filter(message)      end @@ -93,7 +93,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.RejectNonPublicTest do          "type" => "Create"        } -      Pleroma.Config.put([:mrf_rejectnonpublic, :allow_direct], false) +      clear_config([:mrf_rejectnonpublic, :allow_direct], false)        assert {:reject, _} = RejectNonPublic.filter(message)      end    end diff --git a/test/pleroma/web/activity_pub/mrf/simple_policy_test.exs b/test/pleroma/web/activity_pub/mrf/simple_policy_test.exs index d7dde62c4..5c0aff26e 100644 --- a/test/pleroma/web/activity_pub/mrf/simple_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/simple_policy_test.exs @@ -1,11 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    use Pleroma.DataCase    import Pleroma.Factory -  alias Pleroma.Config    alias Pleroma.Web.ActivityPub.MRF.SimplePolicy    alias Pleroma.Web.CommonAPI @@ -25,7 +24,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :media_removal" do      test "is empty" do -      Config.put([:mrf_simple, :media_removal], []) +      clear_config([:mrf_simple, :media_removal], [])        media_message = build_media_message()        local_message = build_local_message() @@ -34,7 +33,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "has a matching host" do -      Config.put([:mrf_simple, :media_removal], ["remote.instance"]) +      clear_config([:mrf_simple, :media_removal], ["remote.instance"])        media_message = build_media_message()        local_message = build_local_message() @@ -47,7 +46,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "match with wildcard domain" do -      Config.put([:mrf_simple, :media_removal], ["*.remote.instance"]) +      clear_config([:mrf_simple, :media_removal], ["*.remote.instance"])        media_message = build_media_message()        local_message = build_local_message() @@ -62,7 +61,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :media_nsfw" do      test "is empty" do -      Config.put([:mrf_simple, :media_nsfw], []) +      clear_config([:mrf_simple, :media_nsfw], [])        media_message = build_media_message()        local_message = build_local_message() @@ -71,29 +70,23 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "has a matching host" do -      Config.put([:mrf_simple, :media_nsfw], ["remote.instance"]) +      clear_config([:mrf_simple, :media_nsfw], ["remote.instance"])        media_message = build_media_message()        local_message = build_local_message()        assert SimplePolicy.filter(media_message) == -               {:ok, -                media_message -                |> put_in(["object", "tag"], ["foo", "nsfw"]) -                |> put_in(["object", "sensitive"], true)} +               {:ok, put_in(media_message, ["object", "sensitive"], true)}        assert SimplePolicy.filter(local_message) == {:ok, local_message}      end      test "match with wildcard domain" do -      Config.put([:mrf_simple, :media_nsfw], ["*.remote.instance"]) +      clear_config([:mrf_simple, :media_nsfw], ["*.remote.instance"])        media_message = build_media_message()        local_message = build_local_message()        assert SimplePolicy.filter(media_message) == -               {:ok, -                media_message -                |> put_in(["object", "tag"], ["foo", "nsfw"]) -                |> put_in(["object", "sensitive"], true)} +               {:ok, put_in(media_message, ["object", "sensitive"], true)}        assert SimplePolicy.filter(local_message) == {:ok, local_message}      end @@ -113,7 +106,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :report_removal" do      test "is empty" do -      Config.put([:mrf_simple, :report_removal], []) +      clear_config([:mrf_simple, :report_removal], [])        report_message = build_report_message()        local_message = build_local_message() @@ -122,7 +115,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "has a matching host" do -      Config.put([:mrf_simple, :report_removal], ["remote.instance"]) +      clear_config([:mrf_simple, :report_removal], ["remote.instance"])        report_message = build_report_message()        local_message = build_local_message() @@ -131,7 +124,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "match with wildcard domain" do -      Config.put([:mrf_simple, :report_removal], ["*.remote.instance"]) +      clear_config([:mrf_simple, :report_removal], ["*.remote.instance"])        report_message = build_report_message()        local_message = build_local_message() @@ -149,7 +142,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :federated_timeline_removal" do      test "is empty" do -      Config.put([:mrf_simple, :federated_timeline_removal], []) +      clear_config([:mrf_simple, :federated_timeline_removal], [])        {_, ftl_message} = build_ftl_actor_and_message()        local_message = build_local_message() @@ -166,7 +159,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do          |> URI.parse()          |> Map.fetch!(:host) -      Config.put([:mrf_simple, :federated_timeline_removal], [ftl_message_actor_host]) +      clear_config([:mrf_simple, :federated_timeline_removal], [ftl_message_actor_host])        local_message = build_local_message()        assert {:ok, ftl_message} = SimplePolicy.filter(ftl_message) @@ -187,7 +180,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do          |> URI.parse()          |> Map.fetch!(:host) -      Config.put([:mrf_simple, :federated_timeline_removal], ["*." <> ftl_message_actor_host]) +      clear_config([:mrf_simple, :federated_timeline_removal], ["*." <> ftl_message_actor_host])        local_message = build_local_message()        assert {:ok, ftl_message} = SimplePolicy.filter(ftl_message) @@ -210,7 +203,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do        ftl_message = Map.put(ftl_message, "cc", []) -      Config.put([:mrf_simple, :federated_timeline_removal], [ftl_message_actor_host]) +      clear_config([:mrf_simple, :federated_timeline_removal], [ftl_message_actor_host])        assert {:ok, ftl_message} = SimplePolicy.filter(ftl_message)        refute "https://www.w3.org/ns/activitystreams#Public" in ftl_message["to"] @@ -231,7 +224,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :reject" do      test "is empty" do -      Config.put([:mrf_simple, :reject], []) +      clear_config([:mrf_simple, :reject], [])        remote_message = build_remote_message() @@ -239,7 +232,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "activity has a matching host" do -      Config.put([:mrf_simple, :reject], ["remote.instance"]) +      clear_config([:mrf_simple, :reject], ["remote.instance"])        remote_message = build_remote_message() @@ -247,7 +240,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "activity matches with wildcard domain" do -      Config.put([:mrf_simple, :reject], ["*.remote.instance"]) +      clear_config([:mrf_simple, :reject], ["*.remote.instance"])        remote_message = build_remote_message() @@ -255,7 +248,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "actor has a matching host" do -      Config.put([:mrf_simple, :reject], ["remote.instance"]) +      clear_config([:mrf_simple, :reject], ["remote.instance"])        remote_user = build_remote_user() @@ -265,7 +258,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :followers_only" do      test "is empty" do -      Config.put([:mrf_simple, :followers_only], []) +      clear_config([:mrf_simple, :followers_only], [])        {_, ftl_message} = build_ftl_actor_and_message()        local_message = build_local_message() @@ -305,7 +298,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do          |> URI.parse()          |> Map.fetch!(:host) -      Config.put([:mrf_simple, :followers_only], [actor_domain]) +      clear_config([:mrf_simple, :followers_only], [actor_domain])        assert {:ok, new_activity} = SimplePolicy.filter(activity)        assert actor.follower_address in new_activity["cc"] @@ -323,7 +316,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :accept" do      test "is empty" do -      Config.put([:mrf_simple, :accept], []) +      clear_config([:mrf_simple, :accept], [])        local_message = build_local_message()        remote_message = build_remote_message() @@ -333,7 +326,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "is not empty but activity doesn't have a matching host" do -      Config.put([:mrf_simple, :accept], ["non.matching.remote"]) +      clear_config([:mrf_simple, :accept], ["non.matching.remote"])        local_message = build_local_message()        remote_message = build_remote_message() @@ -343,7 +336,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "activity has a matching host" do -      Config.put([:mrf_simple, :accept], ["remote.instance"]) +      clear_config([:mrf_simple, :accept], ["remote.instance"])        local_message = build_local_message()        remote_message = build_remote_message() @@ -353,7 +346,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "activity matches with wildcard domain" do -      Config.put([:mrf_simple, :accept], ["*.remote.instance"]) +      clear_config([:mrf_simple, :accept], ["*.remote.instance"])        local_message = build_local_message()        remote_message = build_remote_message() @@ -363,7 +356,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "actor has a matching host" do -      Config.put([:mrf_simple, :accept], ["remote.instance"]) +      clear_config([:mrf_simple, :accept], ["remote.instance"])        remote_user = build_remote_user() @@ -373,7 +366,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :avatar_removal" do      test "is empty" do -      Config.put([:mrf_simple, :avatar_removal], []) +      clear_config([:mrf_simple, :avatar_removal], [])        remote_user = build_remote_user() @@ -381,7 +374,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "is not empty but it doesn't have a matching host" do -      Config.put([:mrf_simple, :avatar_removal], ["non.matching.remote"]) +      clear_config([:mrf_simple, :avatar_removal], ["non.matching.remote"])        remote_user = build_remote_user() @@ -389,7 +382,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "has a matching host" do -      Config.put([:mrf_simple, :avatar_removal], ["remote.instance"]) +      clear_config([:mrf_simple, :avatar_removal], ["remote.instance"])        remote_user = build_remote_user()        {:ok, filtered} = SimplePolicy.filter(remote_user) @@ -398,7 +391,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "match with wildcard domain" do -      Config.put([:mrf_simple, :avatar_removal], ["*.remote.instance"]) +      clear_config([:mrf_simple, :avatar_removal], ["*.remote.instance"])        remote_user = build_remote_user()        {:ok, filtered} = SimplePolicy.filter(remote_user) @@ -409,7 +402,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    describe "when :banner_removal" do      test "is empty" do -      Config.put([:mrf_simple, :banner_removal], []) +      clear_config([:mrf_simple, :banner_removal], [])        remote_user = build_remote_user() @@ -417,7 +410,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "is not empty but it doesn't have a matching host" do -      Config.put([:mrf_simple, :banner_removal], ["non.matching.remote"]) +      clear_config([:mrf_simple, :banner_removal], ["non.matching.remote"])        remote_user = build_remote_user() @@ -425,7 +418,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "has a matching host" do -      Config.put([:mrf_simple, :banner_removal], ["remote.instance"]) +      clear_config([:mrf_simple, :banner_removal], ["remote.instance"])        remote_user = build_remote_user()        {:ok, filtered} = SimplePolicy.filter(remote_user) @@ -434,7 +427,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "match with wildcard domain" do -      Config.put([:mrf_simple, :banner_removal], ["*.remote.instance"]) +      clear_config([:mrf_simple, :banner_removal], ["*.remote.instance"])        remote_user = build_remote_user()        {:ok, filtered} = SimplePolicy.filter(remote_user) @@ -444,10 +437,10 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    end    describe "when :reject_deletes is empty" do -    setup do: Config.put([:mrf_simple, :reject_deletes], []) +    setup do: clear_config([:mrf_simple, :reject_deletes], [])      test "it accepts deletions even from rejected servers" do -      Config.put([:mrf_simple, :reject], ["remote.instance"]) +      clear_config([:mrf_simple, :reject], ["remote.instance"])        deletion_message = build_remote_deletion_message() @@ -455,7 +448,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "it accepts deletions even from non-whitelisted servers" do -      Config.put([:mrf_simple, :accept], ["non.matching.remote"]) +      clear_config([:mrf_simple, :accept], ["non.matching.remote"])        deletion_message = build_remote_deletion_message() @@ -464,10 +457,10 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    end    describe "when :reject_deletes is not empty but it doesn't have a matching host" do -    setup do: Config.put([:mrf_simple, :reject_deletes], ["non.matching.remote"]) +    setup do: clear_config([:mrf_simple, :reject_deletes], ["non.matching.remote"])      test "it accepts deletions even from rejected servers" do -      Config.put([:mrf_simple, :reject], ["remote.instance"]) +      clear_config([:mrf_simple, :reject], ["remote.instance"])        deletion_message = build_remote_deletion_message() @@ -475,7 +468,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do      end      test "it accepts deletions even from non-whitelisted servers" do -      Config.put([:mrf_simple, :accept], ["non.matching.remote"]) +      clear_config([:mrf_simple, :accept], ["non.matching.remote"])        deletion_message = build_remote_deletion_message() @@ -484,7 +477,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    end    describe "when :reject_deletes has a matching host" do -    setup do: Config.put([:mrf_simple, :reject_deletes], ["remote.instance"]) +    setup do: clear_config([:mrf_simple, :reject_deletes], ["remote.instance"])      test "it rejects the deletion" do        deletion_message = build_remote_deletion_message() @@ -494,7 +487,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SimplePolicyTest do    end    describe "when :reject_deletes match with wildcard domain" do -    setup do: Config.put([:mrf_simple, :reject_deletes], ["*.remote.instance"]) +    setup do: clear_config([:mrf_simple, :reject_deletes], ["*.remote.instance"])      test "it rejects the deletion" do        deletion_message = build_remote_deletion_message() diff --git a/test/pleroma/web/activity_pub/mrf/steal_emoji_policy_test.exs b/test/pleroma/web/activity_pub/mrf/steal_emoji_policy_test.exs index 3f8222736..bae57f29a 100644 --- a/test/pleroma/web/activity_pub/mrf/steal_emoji_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/steal_emoji_policy_test.exs @@ -1,11 +1,12 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do    use Pleroma.DataCase    alias Pleroma.Config +  alias Pleroma.Emoji    alias Pleroma.Web.ActivityPub.MRF.StealEmojiPolicy    setup_all do @@ -14,22 +15,9 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do    end    setup do -    emoji_path = Path.join(Config.get([:instance, :static_dir]), "emoji/stolen") -    File.rm_rf!(emoji_path) -    File.mkdir!(emoji_path) +    emoji_path = [:instance, :static_dir] |> Config.get() |> Path.join("emoji/stolen") -    Pleroma.Emoji.reload() - -    on_exit(fn -> -      File.rm_rf!(emoji_path) -    end) - -    :ok -  end - -  test "does nothing by default" do -    installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end) -    refute "firedfox" in installed_emoji +    Emoji.reload()      message = %{        "type" => "Create", @@ -39,30 +27,79 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do        }      } -    assert {:ok, message} == StealEmojiPolicy.filter(message) +    on_exit(fn -> +      File.rm_rf!(emoji_path) +    end) -    installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end) -    refute "firedfox" in installed_emoji +    [message: message, path: emoji_path]    end -  test "Steals emoji on unknown shortcode from allowed remote host" do -    installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end) -    refute "firedfox" in installed_emoji +  test "does nothing by default", %{message: message} do +    refute "firedfox" in installed() -    message = %{ -      "type" => "Create", -      "object" => %{ -        "emoji" => [{"firedfox", "https://example.org/emoji/firedfox.png"}], -        "actor" => "https://example.org/users/admin" -      } -    } +    assert {:ok, _message} = StealEmojiPolicy.filter(message) + +    refute "firedfox" in installed() +  end -    clear_config([:mrf_steal_emoji, :hosts], ["example.org"]) -    clear_config([:mrf_steal_emoji, :size_limit], 284_468) +  test "Steals emoji on unknown shortcode from allowed remote host", %{ +    message: message, +    path: path +  } do +    refute "firedfox" in installed() +    refute File.exists?(path) -    assert {:ok, message} == StealEmojiPolicy.filter(message) +    clear_config(:mrf_steal_emoji, hosts: ["example.org"], size_limit: 284_468) -    installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end) -    assert "firedfox" in installed_emoji +    assert {:ok, _message} = StealEmojiPolicy.filter(message) + +    assert "firedfox" in installed() +    assert File.exists?(path) + +    assert path +           |> Path.join("firedfox.png") +           |> File.exists?() +  end + +  test "reject shortcode", %{message: message} do +    refute "firedfox" in installed() + +    clear_config(:mrf_steal_emoji, +      hosts: ["example.org"], +      size_limit: 284_468, +      rejected_shortcodes: [~r/firedfox/] +    ) + +    assert {:ok, _message} = StealEmojiPolicy.filter(message) + +    refute "firedfox" in installed() +  end + +  test "reject if size is above the limit", %{message: message} do +    refute "firedfox" in installed() + +    clear_config(:mrf_steal_emoji, hosts: ["example.org"], size_limit: 50_000) + +    assert {:ok, _message} = StealEmojiPolicy.filter(message) + +    refute "firedfox" in installed() +  end + +  test "reject if host returns error", %{message: message} do +    refute "firedfox" in installed() + +    Tesla.Mock.mock(fn %{method: :get, url: "https://example.org/emoji/firedfox.png"} -> +      {:ok, %Tesla.Env{status: 404, body: "Not found"}} +    end) + +    clear_config(:mrf_steal_emoji, hosts: ["example.org"], size_limit: 284_468) + +    ExUnit.CaptureLog.capture_log(fn -> +      assert {:ok, _message} = StealEmojiPolicy.filter(message) +    end) =~ "MRF.StealEmojiPolicy: Failed to fetch https://example.org/emoji/firedfox.png" + +    refute "firedfox" in installed()    end + +  defp installed, do: Emoji.get_all() |> Enum.map(fn {k, _} -> k end)  end diff --git a/test/pleroma/web/activity_pub/mrf/subchain_policy_test.exs b/test/pleroma/web/activity_pub/mrf/subchain_policy_test.exs index fff66cb7e..4f5cc466c 100644 --- a/test/pleroma/web/activity_pub/mrf/subchain_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/subchain_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.SubchainPolicyTest do @@ -16,7 +16,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SubchainPolicyTest do    setup do: clear_config([:mrf_subchain, :match_actor])    test "it matches and processes subchains when the actor matches a configured target" do -    Pleroma.Config.put([:mrf_subchain, :match_actor], %{ +    clear_config([:mrf_subchain, :match_actor], %{        ~r/^https:\/\/banned.com/s => [DropPolicy]      }) @@ -24,7 +24,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.SubchainPolicyTest do    end    test "it doesn't match and process subchains when the actor doesn't match a configured target" do -    Pleroma.Config.put([:mrf_subchain, :match_actor], %{ +    clear_config([:mrf_subchain, :match_actor], %{        ~r/^https:\/\/borked.com/s => [DropPolicy]      }) diff --git a/test/pleroma/web/activity_pub/mrf/tag_policy_test.exs b/test/pleroma/web/activity_pub/mrf/tag_policy_test.exs index ffc30ba62..faaadff79 100644 --- a/test/pleroma/web/activity_pub/mrf/tag_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/tag_policy_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.TagPolicyTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.ActivityPub.MRF.TagPolicy @@ -114,7 +114,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.TagPolicyTest do        except_message = %{          "actor" => actor.ap_id,          "type" => "Create", -        "object" => %{"tag" => ["test", "nsfw"], "attachment" => ["file1"], "sensitive" => true} +        "object" => %{"tag" => ["test"], "attachment" => ["file1"], "sensitive" => true}        }        assert TagPolicy.filter(message) == {:ok, except_message} diff --git a/test/pleroma/web/activity_pub/mrf/user_allow_list_policy_test.exs b/test/pleroma/web/activity_pub/mrf/user_allow_list_policy_test.exs index 8e1ad5bc8..f0432ea42 100644 --- a/test/pleroma/web/activity_pub/mrf/user_allow_list_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/user_allow_list_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.UserAllowListPolicyTest do    use Pleroma.DataCase @@ -17,14 +17,14 @@ defmodule Pleroma.Web.ActivityPub.MRF.UserAllowListPolicyTest do    test "pass filter if allow list isn't empty and user in allow list" do      actor = insert(:user) -    Pleroma.Config.put([:mrf_user_allowlist], %{"localhost" => [actor.ap_id, "test-ap-id"]}) +    clear_config([:mrf_user_allowlist], %{"localhost" => [actor.ap_id, "test-ap-id"]})      message = %{"actor" => actor.ap_id}      assert UserAllowListPolicy.filter(message) == {:ok, message}    end    test "rejected if allow list isn't empty and user not in allow list" do      actor = insert(:user) -    Pleroma.Config.put([:mrf_user_allowlist], %{"localhost" => ["test-ap-id"]}) +    clear_config([:mrf_user_allowlist], %{"localhost" => ["test-ap-id"]})      message = %{"actor" => actor.ap_id}      assert {:reject, _} = UserAllowListPolicy.filter(message)    end diff --git a/test/pleroma/web/activity_pub/mrf/vocabulary_policy_test.exs b/test/pleroma/web/activity_pub/mrf/vocabulary_policy_test.exs index 2bceb67ee..87d1d79b5 100644 --- a/test/pleroma/web/activity_pub/mrf/vocabulary_policy_test.exs +++ b/test/pleroma/web/activity_pub/mrf/vocabulary_policy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do @@ -11,7 +11,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do      setup do: clear_config([:mrf_vocabulary, :accept])      test "it accepts based on parent activity type" do -      Pleroma.Config.put([:mrf_vocabulary, :accept], ["Like"]) +      clear_config([:mrf_vocabulary, :accept], ["Like"])        message = %{          "type" => "Like", @@ -22,7 +22,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do      end      test "it accepts based on child object type" do -      Pleroma.Config.put([:mrf_vocabulary, :accept], ["Create", "Note"]) +      clear_config([:mrf_vocabulary, :accept], ["Create", "Note"])        message = %{          "type" => "Create", @@ -36,7 +36,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do      end      test "it does not accept disallowed child objects" do -      Pleroma.Config.put([:mrf_vocabulary, :accept], ["Create", "Note"]) +      clear_config([:mrf_vocabulary, :accept], ["Create", "Note"])        message = %{          "type" => "Create", @@ -50,7 +50,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do      end      test "it does not accept disallowed parent types" do -      Pleroma.Config.put([:mrf_vocabulary, :accept], ["Announce", "Note"]) +      clear_config([:mrf_vocabulary, :accept], ["Announce", "Note"])        message = %{          "type" => "Create", @@ -68,7 +68,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do      setup do: clear_config([:mrf_vocabulary, :reject])      test "it rejects based on parent activity type" do -      Pleroma.Config.put([:mrf_vocabulary, :reject], ["Like"]) +      clear_config([:mrf_vocabulary, :reject], ["Like"])        message = %{          "type" => "Like", @@ -79,7 +79,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do      end      test "it rejects based on child object type" do -      Pleroma.Config.put([:mrf_vocabulary, :reject], ["Note"]) +      clear_config([:mrf_vocabulary, :reject], ["Note"])        message = %{          "type" => "Create", @@ -93,7 +93,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.VocabularyPolicyTest do      end      test "it passes through objects that aren't disallowed" do -      Pleroma.Config.put([:mrf_vocabulary, :reject], ["Like"]) +      clear_config([:mrf_vocabulary, :reject], ["Like"])        message = %{          "type" => "Announce", diff --git a/test/pleroma/web/activity_pub/mrf_test.exs b/test/pleroma/web/activity_pub/mrf_test.exs index 44a9cf086..61d308b97 100644 --- a/test/pleroma/web/activity_pub/mrf_test.exs +++ b/test/pleroma/web/activity_pub/mrf_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.MRFTest do @@ -68,7 +68,12 @@ defmodule Pleroma.Web.ActivityPub.MRFTest do        clear_config([:mrf, :policies], [Pleroma.Web.ActivityPub.MRF.NoOpPolicy])        expected = %{ -        mrf_policies: ["NoOpPolicy"], +        mrf_policies: ["NoOpPolicy", "HashtagPolicy"], +        mrf_hashtag: %{ +          federated_timeline_removal: [], +          reject: [], +          sensitive: ["nsfw"] +        },          exclusions: false        } @@ -79,8 +84,13 @@ defmodule Pleroma.Web.ActivityPub.MRFTest do        clear_config([:mrf, :policies], [MRFModuleMock])        expected = %{ -        mrf_policies: ["MRFModuleMock"], +        mrf_policies: ["MRFModuleMock", "HashtagPolicy"],          mrf_module_mock: "some config data", +        mrf_hashtag: %{ +          federated_timeline_removal: [], +          reject: [], +          sensitive: ["nsfw"] +        },          exclusions: false        } diff --git a/test/pleroma/web/activity_pub/object_validators/accept_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/accept_validation_test.exs index d6111ba41..ddb302f6e 100644 --- a/test/pleroma/web/activity_pub/object_validators/accept_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/accept_validation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.AcceptValidationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.Builder    alias Pleroma.Web.ActivityPub.ObjectValidator diff --git a/test/pleroma/web/activity_pub/object_validators/announce_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/announce_validation_test.exs index 4771c4698..939922127 100644 --- a/test/pleroma/web/activity_pub/object_validators/announce_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/announce_validation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnnounceValidationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Object    alias Pleroma.Web.ActivityPub.Builder @@ -18,7 +18,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnnounceValidationTest do        announcer = insert(:user)        {:ok, post_activity} = CommonAPI.post(user, %{status: "uguu"}) -      object = Object.normalize(post_activity, false) +      object = Object.normalize(post_activity, fetch: false)        {:ok, valid_announce, []} = Builder.announce(announcer, object)        %{ @@ -81,7 +81,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.AnnounceValidationTest do        {:ok, post_activity} =          CommonAPI.post(user, %{status: "a secret post", visibility: "private"}) -      object = Object.normalize(post_activity, false) +      object = Object.normalize(post_activity, fetch: false)        # Another user can't announce it        {:ok, announce, []} = Builder.announce(announcer, object, public: false) diff --git a/test/pleroma/web/activity_pub/object_validators/article_note_validator_test.exs b/test/pleroma/web/activity_pub/object_validators/article_note_validator_test.exs index cc6dab872..e408c85c3 100644 --- a/test/pleroma/web/activity_pub/object_validators/article_note_validator_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/article_note_validator_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.ArticleNoteValidatorTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.ObjectValidators.ArticleNoteValidator    alias Pleroma.Web.ActivityPub.Utils diff --git a/test/pleroma/web/activity_pub/object_validators/attachment_validator_test.exs b/test/pleroma/web/activity_pub/object_validators/attachment_validator_test.exs index 2e1975a79..b775515e0 100644 --- a/test/pleroma/web/activity_pub/object_validators/attachment_validator_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/attachment_validator_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidatorTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.ActivityPub    alias Pleroma.Web.ActivityPub.ObjectValidators.AttachmentValidator diff --git a/test/pleroma/web/activity_pub/object_validators/block_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/block_validation_test.exs index c08d4b2e8..ad6190892 100644 --- a/test/pleroma/web/activity_pub/object_validators/block_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/block_validation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.BlockValidationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.Builder    alias Pleroma.Web.ActivityPub.ObjectValidator diff --git a/test/pleroma/web/activity_pub/object_validators/chat_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/chat_validation_test.exs index d7e299224..320854187 100644 --- a/test/pleroma/web/activity_pub/object_validators/chat_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/chat_validation_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.ChatValidationTest do @@ -17,7 +17,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ChatValidationTest do        user = insert(:user)        recipient = insert(:user)        {:ok, activity} = CommonAPI.post_chat_message(user, recipient, "hey") -      object = Object.normalize(activity, false) +      object = Object.normalize(activity, fetch: false)        {:ok, create_data, _} = Builder.create(user, object.data, [recipient.ap_id]) @@ -149,7 +149,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.ChatValidationTest do      test "does not validate if the message is longer than the remote_limit", %{        valid_chat_message: valid_chat_message      } do -      Pleroma.Config.put([:instance, :remote_limit], 2) +      clear_config([:instance, :remote_limit], 2)        refute match?({:ok, _object, _meta}, ObjectValidator.validate(valid_chat_message, []))      end diff --git a/test/pleroma/web/activity_pub/object_validators/delete_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/delete_validation_test.exs index 02683b899..7ae4399ed 100644 --- a/test/pleroma/web/activity_pub/object_validators/delete_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/delete_validation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.DeleteValidationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Object    alias Pleroma.Web.ActivityPub.Builder diff --git a/test/pleroma/web/activity_pub/object_validators/emoji_react_handling_test.exs b/test/pleroma/web/activity_pub/object_validators/emoji_react_handling_test.exs index 582e6d785..7fd98266a 100644 --- a/test/pleroma/web/activity_pub/object_validators/emoji_react_handling_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/emoji_react_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.EmojiReactHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.Builder    alias Pleroma.Web.ActivityPub.ObjectValidator diff --git a/test/pleroma/web/activity_pub/object_validators/follow_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/follow_validation_test.exs index 6e1378be2..d2a9b72a5 100644 --- a/test/pleroma/web/activity_pub/object_validators/follow_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/follow_validation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.FollowValidationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.Builder    alias Pleroma.Web.ActivityPub.ObjectValidator diff --git a/test/pleroma/web/activity_pub/object_validators/like_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/like_validation_test.exs index 2c033b7e2..55f67232e 100644 --- a/test/pleroma/web/activity_pub/object_validators/like_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/like_validation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.LikeValidationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.ObjectValidator    alias Pleroma.Web.ActivityPub.ObjectValidators.LikeValidator diff --git a/test/pleroma/web/activity_pub/object_validators/reject_validation_test.exs b/test/pleroma/web/activity_pub/object_validators/reject_validation_test.exs index 370bb6e5c..562656a5f 100644 --- a/test/pleroma/web/activity_pub/object_validators/reject_validation_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/reject_validation_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.RejectValidationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.Builder    alias Pleroma.Web.ActivityPub.ObjectValidator diff --git a/test/pleroma/web/activity_pub/object_validators/undo_handling_test.exs b/test/pleroma/web/activity_pub/object_validators/undo_handling_test.exs index 75bbcc4b6..505ca2d2f 100644 --- a/test/pleroma/web/activity_pub/object_validators/undo_handling_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/undo_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.UndoHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.Builder    alias Pleroma.Web.ActivityPub.ObjectValidator diff --git a/test/pleroma/web/activity_pub/object_validators/update_handling_test.exs b/test/pleroma/web/activity_pub/object_validators/update_handling_test.exs index 5e80cf731..15e4a82cd 100644 --- a/test/pleroma/web/activity_pub/object_validators/update_handling_test.exs +++ b/test/pleroma/web/activity_pub/object_validators/update_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectValidators.UpdateHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.ActivityPub.Builder    alias Pleroma.Web.ActivityPub.ObjectValidator diff --git a/test/pleroma/web/activity_pub/pipeline_test.exs b/test/pleroma/web/activity_pub/pipeline_test.exs index 210a06563..e606fa3d1 100644 --- a/test/pleroma/web/activity_pub/pipeline_test.exs +++ b/test/pleroma/web/activity_pub/pipeline_test.exs @@ -1,16 +1,34 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.PipelineTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true -  import Mock +  import Mox    import Pleroma.Factory +  alias Pleroma.ConfigMock +  alias Pleroma.Web.ActivityPub.ActivityPubMock +  alias Pleroma.Web.ActivityPub.MRFMock +  alias Pleroma.Web.ActivityPub.ObjectValidatorMock +  alias Pleroma.Web.ActivityPub.SideEffectsMock +  alias Pleroma.Web.FederatorMock + +  setup :verify_on_exit! +    describe "common_pipeline/2" do      setup do -      clear_config([:instance, :federating], true) +      ObjectValidatorMock +      |> expect(:validate, fn o, m -> {:ok, o, m} end) + +      MRFMock +      |> expect(:pipeline_filter, fn o, m -> {:ok, o, m} end) + +      SideEffectsMock +      |> expect(:handle, fn o, m -> {:ok, o, m} end) +      |> expect(:handle_after_transaction, fn m -> m end) +        :ok      end @@ -21,159 +39,65 @@ defmodule Pleroma.Web.ActivityPub.PipelineTest do        activity_with_object = %{activity | data: Map.put(activity.data, "object", object)} -      with_mocks([ -        {Pleroma.Web.ActivityPub.ObjectValidator, [], [validate: fn o, m -> {:ok, o, m} end]}, -        { -          Pleroma.Web.ActivityPub.MRF, -          [], -          [pipeline_filter: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.ActivityPub, -          [], -          [persist: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.SideEffects, -          [], -          [ -            handle: fn o, m -> {:ok, o, m} end, -            handle_after_transaction: fn m -> m end -          ] -        }, -        { -          Pleroma.Web.Federator, -          [], -          [publish: fn _o -> :ok end] -        } -      ]) do -        assert {:ok, ^activity, ^meta} = -                 Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity, meta) - -        assert_called(Pleroma.Web.ActivityPub.ObjectValidator.validate(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.MRF.pipeline_filter(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.ActivityPub.persist(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta)) -        refute called(Pleroma.Web.Federator.publish(activity)) -        assert_called(Pleroma.Web.Federator.publish(activity_with_object)) -      end +      ActivityPubMock +      |> expect(:persist, fn _, m -> {:ok, activity, m} end) + +      FederatorMock +      |> expect(:publish, fn ^activity_with_object -> :ok end) + +      ConfigMock +      |> expect(:get, fn [:instance, :federating] -> true end) + +      assert {:ok, ^activity, ^meta} = +               Pleroma.Web.ActivityPub.Pipeline.common_pipeline( +                 activity.data, +                 meta +               )      end      test "it goes through validation, filtering, persisting, side effects and federation for local activities" do        activity = insert(:note_activity)        meta = [local: true] -      with_mocks([ -        {Pleroma.Web.ActivityPub.ObjectValidator, [], [validate: fn o, m -> {:ok, o, m} end]}, -        { -          Pleroma.Web.ActivityPub.MRF, -          [], -          [pipeline_filter: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.ActivityPub, -          [], -          [persist: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.SideEffects, -          [], -          [ -            handle: fn o, m -> {:ok, o, m} end, -            handle_after_transaction: fn m -> m end -          ] -        }, -        { -          Pleroma.Web.Federator, -          [], -          [publish: fn _o -> :ok end] -        } -      ]) do -        assert {:ok, ^activity, ^meta} = -                 Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity, meta) - -        assert_called(Pleroma.Web.ActivityPub.ObjectValidator.validate(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.MRF.pipeline_filter(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.ActivityPub.persist(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta)) -        assert_called(Pleroma.Web.Federator.publish(activity)) -      end +      ActivityPubMock +      |> expect(:persist, fn _, m -> {:ok, activity, m} end) + +      FederatorMock +      |> expect(:publish, fn ^activity -> :ok end) + +      ConfigMock +      |> expect(:get, fn [:instance, :federating] -> true end) + +      assert {:ok, ^activity, ^meta} = +               Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity.data, meta)      end      test "it goes through validation, filtering, persisting, side effects without federation for remote activities" do        activity = insert(:note_activity)        meta = [local: false] -      with_mocks([ -        {Pleroma.Web.ActivityPub.ObjectValidator, [], [validate: fn o, m -> {:ok, o, m} end]}, -        { -          Pleroma.Web.ActivityPub.MRF, -          [], -          [pipeline_filter: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.ActivityPub, -          [], -          [persist: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.SideEffects, -          [], -          [handle: fn o, m -> {:ok, o, m} end, handle_after_transaction: fn m -> m end] -        }, -        { -          Pleroma.Web.Federator, -          [], -          [] -        } -      ]) do -        assert {:ok, ^activity, ^meta} = -                 Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity, meta) - -        assert_called(Pleroma.Web.ActivityPub.ObjectValidator.validate(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.MRF.pipeline_filter(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.ActivityPub.persist(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta)) -      end +      ActivityPubMock +      |> expect(:persist, fn _, m -> {:ok, activity, m} end) + +      ConfigMock +      |> expect(:get, fn [:instance, :federating] -> true end) + +      assert {:ok, ^activity, ^meta} = +               Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity.data, meta)      end      test "it goes through validation, filtering, persisting, side effects without federation for local activities if federation is deactivated" do -      clear_config([:instance, :federating], false) -        activity = insert(:note_activity)        meta = [local: true] -      with_mocks([ -        {Pleroma.Web.ActivityPub.ObjectValidator, [], [validate: fn o, m -> {:ok, o, m} end]}, -        { -          Pleroma.Web.ActivityPub.MRF, -          [], -          [pipeline_filter: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.ActivityPub, -          [], -          [persist: fn o, m -> {:ok, o, m} end] -        }, -        { -          Pleroma.Web.ActivityPub.SideEffects, -          [], -          [handle: fn o, m -> {:ok, o, m} end, handle_after_transaction: fn m -> m end] -        }, -        { -          Pleroma.Web.Federator, -          [], -          [] -        } -      ]) do -        assert {:ok, ^activity, ^meta} = -                 Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity, meta) - -        assert_called(Pleroma.Web.ActivityPub.ObjectValidator.validate(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.MRF.pipeline_filter(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.ActivityPub.persist(activity, meta)) -        assert_called(Pleroma.Web.ActivityPub.SideEffects.handle(activity, meta)) -      end +      ActivityPubMock +      |> expect(:persist, fn _, m -> {:ok, activity, m} end) + +      ConfigMock +      |> expect(:get, fn [:instance, :federating] -> false end) + +      assert {:ok, ^activity, ^meta} = +               Pleroma.Web.ActivityPub.Pipeline.common_pipeline(activity.data, meta)      end    end  end diff --git a/test/pleroma/web/activity_pub/publisher_test.exs b/test/pleroma/web/activity_pub/publisher_test.exs index 3503d25b2..f0ce3d7f2 100644 --- a/test/pleroma/web/activity_pub/publisher_test.exs +++ b/test/pleroma/web/activity_pub/publisher_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.PublisherTest do @@ -322,7 +322,7 @@ defmodule Pleroma.Web.ActivityPub.PublisherTest do        actor = insert(:user)        note_activity = insert(:note_activity, user: actor) -      object = Object.normalize(note_activity) +      object = Object.normalize(note_activity, fetch: false)        activity_path = String.trim_leading(note_activity.data["id"], Pleroma.Web.Endpoint.url())        object_path = String.trim_leading(object.data["id"], Pleroma.Web.Endpoint.url()) diff --git a/test/pleroma/web/activity_pub/relay_test.exs b/test/pleroma/web/activity_pub/relay_test.exs index 3284980f7..2aa07d1b5 100644 --- a/test/pleroma/web/activity_pub/relay_test.exs +++ b/test/pleroma/web/activity_pub/relay_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.RelayTest do @@ -84,7 +84,7 @@ defmodule Pleroma.Web.ActivityPub.RelayTest do               )        Pleroma.Repo.delete(user) -      Cachex.clear(:user_cache) +      User.invalidate_cache(user)        assert {:ok, %Activity{} = activity} = Relay.unfollow(user_ap_id, %{force: true}) diff --git a/test/pleroma/web/activity_pub/side_effects/delete_test.exs b/test/pleroma/web/activity_pub/side_effects/delete_test.exs new file mode 100644 index 000000000..20f0d4b70 --- /dev/null +++ b/test/pleroma/web/activity_pub/side_effects/delete_test.exs @@ -0,0 +1,147 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.ActivityPub.SideEffects.DeleteTest do +  use Oban.Testing, repo: Pleroma.Repo +  use Pleroma.DataCase, async: true + +  alias Pleroma.Activity +  alias Pleroma.Object +  alias Pleroma.Repo +  alias Pleroma.Tests.ObanHelpers +  alias Pleroma.User +  alias Pleroma.Web.ActivityPub.ActivityPub +  alias Pleroma.Web.ActivityPub.Builder +  alias Pleroma.Web.ActivityPub.SideEffects +  alias Pleroma.Web.CommonAPI + +  alias Pleroma.LoggerMock +  alias Pleroma.Web.ActivityPub.ActivityPubMock + +  import Mox +  import Pleroma.Factory + +  describe "user deletion" do +    setup do +      user = insert(:user) + +      {:ok, delete_user_data, _meta} = Builder.delete(user, user.ap_id) +      {:ok, delete_user, _meta} = ActivityPub.persist(delete_user_data, local: true) + +      %{ +        user: user, +        delete_user: delete_user +      } +    end + +    test "it handles user deletions", %{delete_user: delete, user: user} do +      {:ok, _delete, _} = SideEffects.handle(delete) +      ObanHelpers.perform_all() + +      refute User.get_cached_by_ap_id(user.ap_id).is_active +    end +  end + +  describe "object deletion" do +    setup do +      user = insert(:user) +      other_user = insert(:user) + +      {:ok, op} = CommonAPI.post(other_user, %{status: "big oof"}) +      {:ok, post} = CommonAPI.post(user, %{status: "hey", in_reply_to_id: op}) +      {:ok, favorite} = CommonAPI.favorite(user, post.id) +      object = Object.normalize(post, fetch: false) +      {:ok, delete_data, _meta} = Builder.delete(user, object.data["id"]) +      {:ok, delete, _meta} = ActivityPub.persist(delete_data, local: true) + +      %{ +        user: user, +        delete: delete, +        post: post, +        object: object, +        op: op, +        favorite: favorite +      } +    end + +    test "it handles object deletions", %{ +      delete: delete, +      post: post, +      object: object, +      user: user, +      op: op, +      favorite: favorite +    } do +      object_id = object.id +      user_id = user.id + +      ActivityPubMock +      |> expect(:stream_out, fn ^delete -> nil end) +      |> expect(:stream_out_participations, fn %Object{id: ^object_id}, %User{id: ^user_id} -> +        nil +      end) + +      {:ok, _delete, _} = SideEffects.handle(delete) +      user = User.get_cached_by_ap_id(object.data["actor"]) + +      object = Object.get_by_id(object.id) +      assert object.data["type"] == "Tombstone" +      refute Activity.get_by_id(post.id) +      refute Activity.get_by_id(favorite.id) + +      user = User.get_by_id(user.id) +      assert user.note_count == 0 + +      object = Object.normalize(op.data["object"], fetch: false) + +      assert object.data["repliesCount"] == 0 +    end + +    test "it handles object deletions when the object itself has been pruned", %{ +      delete: delete, +      post: post, +      object: object, +      user: user, +      op: op +    } do +      object_id = object.id +      user_id = user.id + +      ActivityPubMock +      |> expect(:stream_out, fn ^delete -> nil end) +      |> expect(:stream_out_participations, fn %Object{id: ^object_id}, %User{id: ^user_id} -> +        nil +      end) + +      {:ok, _delete, _} = SideEffects.handle(delete) +      user = User.get_cached_by_ap_id(object.data["actor"]) + +      object = Object.get_by_id(object.id) +      assert object.data["type"] == "Tombstone" +      refute Activity.get_by_id(post.id) + +      user = User.get_by_id(user.id) +      assert user.note_count == 0 + +      object = Object.normalize(op.data["object"], fetch: false) + +      assert object.data["repliesCount"] == 0 +    end + +    test "it logs issues with objects deletion", %{ +      delete: delete, +      object: object +    } do +      {:ok, _object} = +        object +        |> Object.change(%{data: Map.delete(object.data, "actor")}) +        |> Repo.update() + +      LoggerMock +      |> expect(:error, fn str -> assert str =~ "The object doesn't have an actor" end) + +      {:error, :no_object_actor} = SideEffects.handle(delete) +    end +  end +end diff --git a/test/pleroma/web/activity_pub/side_effects_test.exs b/test/pleroma/web/activity_pub/side_effects_test.exs index 297fc0b84..13167f50a 100644 --- a/test/pleroma/web/activity_pub/side_effects_test.exs +++ b/test/pleroma/web/activity_pub/side_effects_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.SideEffectsTest do @@ -19,7 +19,6 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do    alias Pleroma.Web.ActivityPub.SideEffects    alias Pleroma.Web.CommonAPI -  import ExUnit.CaptureLog    import Mock    import Pleroma.Factory @@ -131,115 +130,6 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do      end    end -  describe "delete objects" do -    setup do -      user = insert(:user) -      other_user = insert(:user) - -      {:ok, op} = CommonAPI.post(other_user, %{status: "big oof"}) -      {:ok, post} = CommonAPI.post(user, %{status: "hey", in_reply_to_id: op}) -      {:ok, favorite} = CommonAPI.favorite(user, post.id) -      object = Object.normalize(post) -      {:ok, delete_data, _meta} = Builder.delete(user, object.data["id"]) -      {:ok, delete_user_data, _meta} = Builder.delete(user, user.ap_id) -      {:ok, delete, _meta} = ActivityPub.persist(delete_data, local: true) -      {:ok, delete_user, _meta} = ActivityPub.persist(delete_user_data, local: true) - -      %{ -        user: user, -        delete: delete, -        post: post, -        object: object, -        delete_user: delete_user, -        op: op, -        favorite: favorite -      } -    end - -    test "it handles object deletions", %{ -      delete: delete, -      post: post, -      object: object, -      user: user, -      op: op, -      favorite: favorite -    } do -      with_mock Pleroma.Web.ActivityPub.ActivityPub, [:passthrough], -        stream_out: fn _ -> nil end, -        stream_out_participations: fn _, _ -> nil end do -        {:ok, delete, _} = SideEffects.handle(delete) -        user = User.get_cached_by_ap_id(object.data["actor"]) - -        assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out(delete)) -        assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out_participations(object, user)) -      end - -      object = Object.get_by_id(object.id) -      assert object.data["type"] == "Tombstone" -      refute Activity.get_by_id(post.id) -      refute Activity.get_by_id(favorite.id) - -      user = User.get_by_id(user.id) -      assert user.note_count == 0 - -      object = Object.normalize(op.data["object"], false) - -      assert object.data["repliesCount"] == 0 -    end - -    test "it handles object deletions when the object itself has been pruned", %{ -      delete: delete, -      post: post, -      object: object, -      user: user, -      op: op -    } do -      with_mock Pleroma.Web.ActivityPub.ActivityPub, [:passthrough], -        stream_out: fn _ -> nil end, -        stream_out_participations: fn _, _ -> nil end do -        {:ok, delete, _} = SideEffects.handle(delete) -        user = User.get_cached_by_ap_id(object.data["actor"]) - -        assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out(delete)) -        assert called(Pleroma.Web.ActivityPub.ActivityPub.stream_out_participations(object, user)) -      end - -      object = Object.get_by_id(object.id) -      assert object.data["type"] == "Tombstone" -      refute Activity.get_by_id(post.id) - -      user = User.get_by_id(user.id) -      assert user.note_count == 0 - -      object = Object.normalize(op.data["object"], false) - -      assert object.data["repliesCount"] == 0 -    end - -    test "it handles user deletions", %{delete_user: delete, user: user} do -      {:ok, _delete, _} = SideEffects.handle(delete) -      ObanHelpers.perform_all() - -      assert User.get_cached_by_ap_id(user.ap_id).deactivated -    end - -    test "it logs issues with objects deletion", %{ -      delete: delete, -      object: object -    } do -      {:ok, object} = -        object -        |> Object.change(%{data: Map.delete(object.data, "actor")}) -        |> Repo.update() - -      Object.invalid_object_cache(object) - -      assert capture_log(fn -> -               {:error, :no_object_actor} = SideEffects.handle(delete) -             end) =~ "object doesn't have an actor" -    end -  end -    describe "EmojiReact objects" do      setup do        poster = insert(:user) @@ -269,20 +159,12 @@ defmodule Pleroma.Web.ActivityPub.SideEffectsTest do    describe "delete users with confirmation pending" do      setup do -      user = insert(:user, confirmation_pending: true) +      user = insert(:user, is_confirmed: false)        {:ok, delete_user_data, _meta} = Builder.delete(user, user.ap_id)        {:ok, delete_user, _meta} = ActivityPub.persist(delete_user_data, local: true)        {:ok, delete: delete_user, user: user}      end -    test "when activation is not required", %{delete: delete, user: user} do -      clear_config([:instance, :account_activation_required], false) -      {:ok, _, _} = SideEffects.handle(delete) -      ObanHelpers.perform_all() - -      assert User.get_cached_by_id(user.id).deactivated -    end -      test "when activation is required", %{delete: delete, user: user} do        clear_config([:instance, :account_activation_required], true)        {:ok, _, _} = SideEffects.handle(delete) diff --git a/test/pleroma/web/activity_pub/transmogrifier/accept_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/accept_handling_test.exs index 485216487..58490076d 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/accept_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/accept_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.AcceptHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.User    alias Pleroma.Web.ActivityPub.Transmogrifier diff --git a/test/pleroma/web/activity_pub/transmogrifier/add_remove_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/add_remove_handling_test.exs new file mode 100644 index 000000000..fc7757125 --- /dev/null +++ b/test/pleroma/web/activity_pub/transmogrifier/add_remove_handling_test.exs @@ -0,0 +1,172 @@ +defmodule Pleroma.Web.ActivityPub.Transmogrifier.AddRemoveHandlingTest do +  use Oban.Testing, repo: Pleroma.Repo +  use Pleroma.DataCase, async: true + +  require Pleroma.Constants + +  import Pleroma.Factory + +  alias Pleroma.User +  alias Pleroma.Web.ActivityPub.Transmogrifier + +  test "it accepts Add/Remove activities" do +    user = +      "test/fixtures/users_mock/user.json" +      |> File.read!() +      |> String.replace("{{nickname}}", "lain") + +    object_id = "c61d6733-e256-4fe1-ab13-1e369789423f" + +    object = +      "test/fixtures/statuses/note.json" +      |> File.read!() +      |> String.replace("{{nickname}}", "lain") +      |> String.replace("{{object_id}}", object_id) + +    object_url = "https://example.com/objects/#{object_id}" + +    actor = "https://example.com/users/lain" + +    Tesla.Mock.mock(fn +      %{ +        method: :get, +        url: ^actor +      } -> +        %Tesla.Env{ +          status: 200, +          body: user, +          headers: [{"content-type", "application/activity+json"}] +        } + +      %{ +        method: :get, +        url: ^object_url +      } -> +        %Tesla.Env{ +          status: 200, +          body: object, +          headers: [{"content-type", "application/activity+json"}] +        } + +      %{method: :get, url: "https://example.com/users/lain/collections/featured"} -> +        %Tesla.Env{ +          status: 200, +          body: +            "test/fixtures/users_mock/masto_featured.json" +            |> File.read!() +            |> String.replace("{{domain}}", "example.com") +            |> String.replace("{{nickname}}", "lain"), +          headers: [{"content-type", "application/activity+json"}] +        } +    end) + +    message = %{ +      "id" => "https://example.com/objects/d61d6733-e256-4fe1-ab13-1e369789423f", +      "actor" => actor, +      "object" => object_url, +      "target" => "https://example.com/users/lain/collections/featured", +      "type" => "Add", +      "to" => [Pleroma.Constants.as_public()], +      "cc" => ["https://example.com/users/lain/followers"] +    } + +    assert {:ok, activity} = Transmogrifier.handle_incoming(message) +    assert activity.data == message +    user = User.get_cached_by_ap_id(actor) +    assert user.pinned_objects[object_url] + +    remove = %{ +      "id" => "http://localhost:400/objects/d61d6733-e256-4fe1-ab13-1e369789423d", +      "actor" => actor, +      "object" => object_url, +      "target" => "https://example.com/users/lain/collections/featured", +      "type" => "Remove", +      "to" => [Pleroma.Constants.as_public()], +      "cc" => ["https://example.com/users/lain/followers"] +    } + +    assert {:ok, activity} = Transmogrifier.handle_incoming(remove) +    assert activity.data == remove + +    user = refresh_record(user) +    refute user.pinned_objects[object_url] +  end + +  test "Add/Remove activities for remote users without featured address" do +    user = insert(:user, local: false, domain: "example.com") + +    user = +      user +      |> Ecto.Changeset.change(featured_address: nil) +      |> Repo.update!() + +    %{host: host} = URI.parse(user.ap_id) + +    user_data = +      "test/fixtures/users_mock/user.json" +      |> File.read!() +      |> String.replace("{{nickname}}", user.nickname) + +    object_id = "c61d6733-e256-4fe1-ab13-1e369789423f" + +    object = +      "test/fixtures/statuses/note.json" +      |> File.read!() +      |> String.replace("{{nickname}}", user.nickname) +      |> String.replace("{{object_id}}", object_id) + +    object_url = "https://#{host}/objects/#{object_id}" + +    actor = "https://#{host}/users/#{user.nickname}" + +    featured = "https://#{host}/users/#{user.nickname}/collections/featured" + +    Tesla.Mock.mock(fn +      %{ +        method: :get, +        url: ^actor +      } -> +        %Tesla.Env{ +          status: 200, +          body: user_data, +          headers: [{"content-type", "application/activity+json"}] +        } + +      %{ +        method: :get, +        url: ^object_url +      } -> +        %Tesla.Env{ +          status: 200, +          body: object, +          headers: [{"content-type", "application/activity+json"}] +        } + +      %{method: :get, url: ^featured} -> +        %Tesla.Env{ +          status: 200, +          body: +            "test/fixtures/users_mock/masto_featured.json" +            |> File.read!() +            |> String.replace("{{domain}}", "#{host}") +            |> String.replace("{{nickname}}", user.nickname), +          headers: [{"content-type", "application/activity+json"}] +        } +    end) + +    message = %{ +      "id" => "https://#{host}/objects/d61d6733-e256-4fe1-ab13-1e369789423f", +      "actor" => actor, +      "object" => object_url, +      "target" => "https://#{host}/users/#{user.nickname}/collections/featured", +      "type" => "Add", +      "to" => [Pleroma.Constants.as_public()], +      "cc" => ["https://#{host}/users/#{user.nickname}/followers"] +    } + +    assert {:ok, activity} = Transmogrifier.handle_incoming(message) +    assert activity.data == message +    user = User.get_cached_by_ap_id(actor) +    assert user.pinned_objects[object_url] +  end +end diff --git a/test/pleroma/web/activity_pub/transmogrifier/announce_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/announce_handling_test.exs index c06bbc5e9..1886fea3f 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/announce_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/announce_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do @@ -130,7 +130,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do      assert data["id"] ==               "http://mastodon.example.org/users/admin/statuses/99542391527669785/activity" -    object = Object.normalize(data["object"]) +    object = Object.normalize(data["object"], fetch: false)      assert object.data["id"] == "http://mastodon.example.org/@admin/99541947525187368"      assert object.data["content"] == "this is a private toot" @@ -158,7 +158,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnnounceHandlingTest do      data =        File.read!("test/fixtures/mastodon-announce.json")        |> Jason.decode!() -      |> Map.put("object", Object.normalize(activity).data["id"]) +      |> Map.put("object", Object.normalize(activity, fetch: false).data["id"])        |> Map.put("to", ["http://mastodon.example.org/users/admin/followers"])        |> Map.put("cc", []) diff --git a/test/pleroma/web/activity_pub/transmogrifier/answer_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/answer_handling_test.exs index a1c2ba28a..9c2ef547b 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/answer_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/answer_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnswerHandlingTest do @@ -26,7 +26,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnswerHandlingTest do          poll: %{options: ["suya", "suya.", "suya.."], expires_in: 10}        }) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert object.data["repliesCount"] == nil      data = @@ -37,7 +37,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnswerHandlingTest do        |> Kernel.put_in(["object", "to"], user.ap_id)      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    answer_object = Object.normalize(activity) +    answer_object = Object.normalize(activity, fetch: false)      assert answer_object.data["type"] == "Answer"      assert answer_object.data["inReplyTo"] == object.data["id"] @@ -62,7 +62,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AnswerHandlingTest do          poll: %{options: ["suya", "suya.", "suya.."], expires_in: 10}        }) -    poll_object = Object.normalize(poll_activity) +    poll_object = Object.normalize(poll_activity, fetch: false)      # TODO: Replace with CommonAPI vote creation when implemented      data =        File.read!("test/fixtures/mastodon-vote.json") diff --git a/test/pleroma/web/activity_pub/transmogrifier/article_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/article_handling_test.exs index b0ae804c5..5dbc5eb95 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/article_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/article_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.ArticleHandlingTest do @@ -25,7 +25,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.ArticleHandlingTest do      {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -    object = Object.normalize(data["object"]) +    object = Object.normalize(data["object"], fetch: false)      assert object.data["name"] == "The end is near: Mastodon plans to drop OStatus support" @@ -75,7 +75,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.ArticleHandlingTest do      data = File.read!("test/fixtures/prismo-url-map.json") |> Jason.decode!()      {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -    object = Object.normalize(data["object"]) +    object = Object.normalize(data["object"], fetch: false)      assert object.data["url"] == "https://prismo.news/posts/83"    end diff --git a/test/pleroma/web/activity_pub/transmogrifier/audio_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/audio_handling_test.exs index 7a2ac5d4d..e733f167d 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/audio_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/audio_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.AudioHandlingTest do @@ -35,7 +35,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AudioHandlingTest do      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert object.data["title"] == "lain radio episode 1"      assert object.data["artist"] == "lain" @@ -57,7 +57,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.AudioHandlingTest do      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    assert object = Object.normalize(activity, false) +    assert object = Object.normalize(activity, fetch: false)      assert object.data["to"] == ["https://www.w3.org/ns/activitystreams#Public"] diff --git a/test/pleroma/web/activity_pub/transmogrifier/block_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/block_handling_test.exs index 679c33c6c..70da06d2e 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/block_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/block_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.BlockHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.User diff --git a/test/pleroma/web/activity_pub/transmogrifier/chat_message_test.exs b/test/pleroma/web/activity_pub/transmogrifier/chat_message_test.exs index 2adaa1ade..958675835 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/chat_message_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/chat_message_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.ChatMessageTest do @@ -134,7 +134,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.ChatMessageTest do            ap_id: data["actor"],            local: false,            last_refreshed_at: DateTime.utc_now(), -          deactivated: true +          is_active: false          )        _recipient = insert(:user, ap_id: List.first(data["to"]), local: true) diff --git a/test/pleroma/web/activity_pub/transmogrifier/delete_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/delete_handling_test.exs index cffaa7c44..b7160bf58 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/delete_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/delete_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do @@ -40,7 +40,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do      assert actor == deleting_user.ap_id      # Objects are replaced by a tombstone object. -    object = Object.normalize(activity.data["object"]) +    object = Object.normalize(activity.data["object"], fetch: false)      assert object.data["type"] == "Tombstone"    end @@ -48,9 +48,10 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do      activity = insert(:note_activity)      {:ok, object} = -      Object.normalize(activity.data["object"]) +      Object.normalize(activity.data["object"], fetch: false)        |> Repo.delete() +    # TODO: mock cachex      Cachex.del(:object_cache, "object:#{object.data["id"]}")      deleting_user = insert(:user) @@ -96,7 +97,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.DeleteHandlingTest do      {:ok, _} = Transmogrifier.handle_incoming(data)      ObanHelpers.perform_all() -    assert User.get_cached_by_ap_id(ap_id).deactivated +    refute User.get_cached_by_ap_id(ap_id).is_active    end    test "it fails for incoming user deletes with spoofed origin" do diff --git a/test/pleroma/web/activity_pub/transmogrifier/emoji_react_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/emoji_react_handling_test.exs index aea4ed6f8..20424ee82 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/emoji_react_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/emoji_react_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.EmojiReactHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.Object diff --git a/test/pleroma/web/activity_pub/transmogrifier/event_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/event_handling_test.exs index d7c55cfbe..c4879fda1 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/event_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/event_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.EventHandlingTest do diff --git a/test/pleroma/web/activity_pub/transmogrifier/follow_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/follow_handling_test.exs index 985c26def..604444a4c 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/follow_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/follow_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.FollowHandlingTest do @@ -133,7 +133,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.FollowHandlingTest do      end      test "it rejects incoming follow requests from blocked users when deny_follow_blocked is enabled" do -      Pleroma.Config.put([:user, :deny_follow_blocked], true) +      clear_config([:user, :deny_follow_blocked], true)        user = insert(:user)        {:ok, target} = User.get_or_fetch("http://mastodon.example.org/users/admin") diff --git a/test/pleroma/web/activity_pub/transmogrifier/like_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/like_handling_test.exs index 967bad151..57d74349a 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/like_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/like_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.LikeHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.Web.ActivityPub.Transmogrifier diff --git a/test/pleroma/web/activity_pub/transmogrifier/note_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/note_handling_test.exs index b4a006aec..deb956410 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/note_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/note_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do @@ -28,7 +28,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        data = File.read!("test/fixtures/kroeg-array-less-emoji.json") |> Jason.decode!()        {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -      object = Object.normalize(data["object"]) +      object = Object.normalize(data["object"], fetch: false)        assert object.data["emoji"] == %{                 "icon_e_smile" => "https://puckipedia.com/forum/images/smilies/icon_e_smile.png" @@ -37,9 +37,10 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        data = File.read!("test/fixtures/kroeg-array-less-hashtag.json") |> Jason.decode!()        {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -      object = Object.normalize(data["object"]) +      object = Object.normalize(data["object"], fetch: false) -      assert "test" in object.data["tag"] +      assert "test" in Object.tags(object) +      assert Object.hashtags(object) == ["test"]      end      test "it cleans up incoming notices which are not really DMs" do @@ -66,7 +67,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        assert data["to"] == []        assert data["cc"] == to -      object_data = Object.normalize(activity).data +      object_data = Object.normalize(activity, fetch: false).data        assert object_data["to"] == []        assert object_data["cc"] == to @@ -78,7 +79,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        data =          File.read!("test/fixtures/mastodon-post-activity.json")          |> Jason.decode!() -        |> Map.put("object", Object.normalize(activity).data) +        |> Map.put("object", Object.normalize(activity, fetch: false).data)        {:ok, returned_activity} = Transmogrifier.handle_incoming(data) @@ -97,7 +98,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        data = Map.put(data, "object", object)        {:ok, returned_activity} = Transmogrifier.handle_incoming(data) -      returned_object = Object.normalize(returned_activity, false) +      returned_object = Object.normalize(returned_activity, fetch: false)        assert %Activity{} =                 Activity.get_create_by_object_ap_id( @@ -123,7 +124,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do          allowed_thread_distance?: fn _ -> false end do          {:ok, returned_activity} = Transmogrifier.handle_incoming(data) -        returned_object = Object.normalize(returned_activity, false) +        returned_object = Object.normalize(returned_activity, fetch: false)          refute Activity.get_create_by_object_ap_id(                   "tag:shitposter.club,2017-05-05:noticeId=2827873:objectType=comment" @@ -154,7 +155,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do      test "it does not work for deactivated users" do        data = File.read!("test/fixtures/mastodon-post-activity.json") |> Jason.decode!() -      insert(:user, ap_id: data["actor"], deactivated: true) +      insert(:user, ap_id: data["actor"], is_active: false)        assert {:error, _} = Transmogrifier.handle_incoming(data)      end @@ -179,7 +180,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        assert data["actor"] == "http://mastodon.example.org/users/admin" -      object_data = Object.normalize(data["object"]).data +      object_data = Object.normalize(data["object"], fetch: false).data        assert object_data["id"] ==                 "http://mastodon.example.org/users/admin/statuses/99512778738411822" @@ -209,7 +210,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -      object_data = Object.normalize(data["object"], false).data +      object_data = Object.normalize(data["object"], fetch: false).data        assert object_data["sensitive"] == true      end @@ -218,16 +219,17 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        data = File.read!("test/fixtures/mastodon-post-activity-hashtag.json") |> Jason.decode!()        {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -      object = Object.normalize(data["object"]) +      object = Object.normalize(data["object"], fetch: false) -      assert Enum.at(object.data["tag"], 2) == "moo" +      assert Enum.at(Object.tags(object), 2) == "moo" +      assert Object.hashtags(object) == ["moo"]      end      test "it works for incoming notices with contentMap" do        data = File.read!("test/fixtures/mastodon-post-activity-contentmap.json") |> Jason.decode!()        {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -      object = Object.normalize(data["object"]) +      object = Object.normalize(data["object"], fetch: false)        assert object.data["content"] ==                 "<p><span class=\"h-card\"><a href=\"http://localtesting.pleroma.lol/users/lain\" class=\"u-url mention\">@<span>lain</span></a></span></p>" @@ -237,7 +239,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        data = File.read!("test/fixtures/kroeg-post-activity.json") |> Jason.decode!()        {:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data) -      object = Object.normalize(data["object"]) +      object = Object.normalize(data["object"], fetch: false)        assert object.data["content"] ==                 "<p>henlo from my Psion netBook</p><p>message sent from my Psion netBook</p>" @@ -415,7 +417,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        data: data,        items: items      } do -      Pleroma.Config.put([:instance, :federation_incoming_replies_max_depth], 10) +      clear_config([:instance, :federation_incoming_replies_max_depth], 10)        {:ok, _activity} = Transmogrifier.handle_incoming(data) @@ -427,7 +429,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do      test "does NOT schedule background fetching of `replies` beyond max thread depth limit allows",           %{data: data} do -      Pleroma.Config.put([:instance, :federation_incoming_replies_max_depth], 0) +      clear_config([:instance, :federation_incoming_replies_max_depth], 0)        {:ok, _activity} = Transmogrifier.handle_incoming(data) @@ -464,7 +466,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do        federation_output: federation_output,        replies_uris: replies_uris      } do -      Pleroma.Config.put([:instance, :federation_incoming_replies_max_depth], 1) +      clear_config([:instance, :federation_incoming_replies_max_depth], 1)        {:ok, _activity} = Transmogrifier.handle_incoming(federation_output) @@ -476,7 +478,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do      test "does NOT schedule background fetching of `replies` beyond max thread depth limit allows",           %{federation_output: federation_output} do -      Pleroma.Config.put([:instance, :federation_incoming_replies_max_depth], 0) +      clear_config([:instance, :federation_incoming_replies_max_depth], 0)        {:ok, _activity} = Transmogrifier.handle_incoming(federation_output) @@ -551,7 +553,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do      end      test "returns object with inReplyTo when denied incoming reply", %{data: data} do -      Pleroma.Config.put([:instance, :federation_incoming_replies_max_depth], 0) +      clear_config([:instance, :federation_incoming_replies_max_depth], 0)        object_with_reply =          Map.put(data["object"], "inReplyTo", "https://shitposter.club/notice/2827873") @@ -585,7 +587,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do            "https://mstdn.io/users/mayuutann/statuses/99568293732299394"          ) -      Pleroma.Config.put([:instance, :federation_incoming_replies_max_depth], 5) +      clear_config([:instance, :federation_incoming_replies_max_depth], 5)        modified_object = Transmogrifier.fix_in_reply_to(object_with_reply)        assert modified_object["inReplyTo"] == @@ -725,7 +727,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do            in_reply_to_status_id: id1          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        replies_uris = Enum.map([self_reply1, self_reply2], fn a -> a.object.data["id"] end)        assert %{"type" => "Collection", "items" => ^replies_uris} = diff --git a/test/pleroma/web/activity_pub/transmogrifier/question_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/question_handling_test.exs index 47f92cf4d..32cf51e59 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/question_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/question_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.QuestionHandlingTest do @@ -22,7 +22,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.QuestionHandlingTest do      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    object = Object.normalize(activity, false) +    object = Object.normalize(activity, fetch: false)      assert object.data["url"] == "https://mastodon.sdf.org/@rinpatch/102070944809637304" @@ -65,7 +65,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.QuestionHandlingTest do      {:ok, reply_activity} = CommonAPI.post(user, %{status: "hewwo", in_reply_to_id: activity.id}) -    reply_object = Object.normalize(reply_activity, false) +    reply_object = Object.normalize(reply_activity, fetch: false)      assert reply_object.data["context"] == object.data["context"]      assert reply_object.data["context_id"] == object.data["context_id"] @@ -101,7 +101,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.QuestionHandlingTest do        |> Kernel.put_in(["object", "oneOf"], options)      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    object = Object.normalize(activity, false) +    object = Object.normalize(activity, fetch: false)      assert Enum.sort(object.data["oneOf"]) == Enum.sort(options)    end @@ -147,7 +147,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.QuestionHandlingTest do        |> Kernel.put_in(["object", "tag"], tag)      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    object = Object.normalize(activity, false) +    object = Object.normalize(activity, fetch: false)      assert object.data["oneOf"] == options diff --git a/test/pleroma/web/activity_pub/transmogrifier/reject_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/reject_handling_test.exs index 5a3bef792..355e664d4 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/reject_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/reject_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.RejectHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.User diff --git a/test/pleroma/web/activity_pub/transmogrifier/undo_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/undo_handling_test.exs index fcfc7b4b6..f6e40722c 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/undo_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/undo_handling_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.UndoHandlingTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.Object diff --git a/test/pleroma/web/activity_pub/transmogrifier/user_update_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/user_update_handling_test.exs index c62d5e139..b1a064772 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/user_update_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/user_update_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.UserUpdateHandlingTest do @@ -103,7 +103,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.UserUpdateHandlingTest do               %{"name" => "foo1", "value" => "updated"}             ] -    Pleroma.Config.put([:instance, :max_remote_account_fields], 2) +    clear_config([:instance, :max_remote_account_fields], 2)      update_data =        update_data diff --git a/test/pleroma/web/activity_pub/transmogrifier/video_handling_test.exs b/test/pleroma/web/activity_pub/transmogrifier/video_handling_test.exs index 57411fafa..6ddf7c172 100644 --- a/test/pleroma/web/activity_pub/transmogrifier/video_handling_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier/video_handling_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.Transmogrifier.VideoHandlingTest do @@ -24,7 +24,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.VideoHandlingTest do      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    assert object = Object.normalize(activity, false) +    assert object = Object.normalize(activity, fetch: false)      assert object.data["content"] == nil    end @@ -34,7 +34,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.VideoHandlingTest do      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    assert object = Object.normalize(activity, false) +    assert object = Object.normalize(activity, fetch: false)      assert object.data["content"] ==               "<p>Après avoir mené avec un certain succès la campagne « Dégooglisons Internet » en 2014, l’association Framasoft annonce fin 2019 arrêter progressivement un certain nombre de ses services alternatifs aux GAFAM. Pourquoi ?</p><p>Transcription par @aprilorg ici : <a href=\"https://www.april.org/deframasoftisons-internet-pierre-yves-gosset-framasoft\">https://www.april.org/deframasoftisons-internet-pierre-yves-gosset-framasoft</a></p>" @@ -70,7 +70,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.VideoHandlingTest do      {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) -    assert object = Object.normalize(activity, false) +    assert object = Object.normalize(activity, fetch: false)      assert object.data["attachment"] == [               %{ @@ -92,4 +92,34 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.VideoHandlingTest do      assert object.data["url"] ==               "https://framatube.org/videos/watch/6050732a-8a7a-43d4-a6cd-809525a1d206"    end + +  test "it works for peertube videos with only their mpegURL map" do +    data = +      File.read!("test/fixtures/peertube/video-object-mpegURL-only.json") +      |> Jason.decode!() + +    {:ok, %Activity{local: false} = activity} = Transmogrifier.handle_incoming(data) + +    assert object = Object.normalize(activity, fetch: false) + +    assert object.data["attachment"] == [ +             %{ +               "type" => "Link", +               "mediaType" => "video/mp4", +               "name" => nil, +               "blurhash" => nil, +               "url" => [ +                 %{ +                   "href" => +                     "https://peertube.stream/static/streaming-playlists/hls/abece3c3-b9c6-47f4-8040-f3eed8c602e6/abece3c3-b9c6-47f4-8040-f3eed8c602e6-1080-fragmented.mp4", +                   "mediaType" => "video/mp4", +                   "type" => "Link" +                 } +               ] +             } +           ] + +    assert object.data["url"] == +             "https://peertube.stream/videos/watch/abece3c3-b9c6-47f4-8040-f3eed8c602e6" +  end  end diff --git a/test/pleroma/web/activity_pub/transmogrifier_test.exs b/test/pleroma/web/activity_pub/transmogrifier_test.exs index 66ea7664a..4c3fcb44a 100644 --- a/test/pleroma/web/activity_pub/transmogrifier_test.exs +++ b/test/pleroma/web/activity_pub/transmogrifier_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do @@ -56,7 +56,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        other_user = insert(:user)        {:ok, activity} = CommonAPI.post(user, %{status: "test post"}) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        note_obj = %{          "type" => "Note", @@ -153,15 +153,6 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        end      end -    test "it adds the sensitive property" do -      user = insert(:user) - -      {:ok, activity} = CommonAPI.post(user, %{status: "#nsfw hey"}) -      {:ok, modified} = Transmogrifier.prepare_outgoing(activity.data) - -      assert modified["object"]["sensitive"] -    end -      test "it adds the json-ld context and the conversation property" do        user = insert(:user) @@ -202,7 +193,20 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do      test "it strips internal fields" do        user = insert(:user) -      {:ok, activity} = CommonAPI.post(user, %{status: "#2hu :firefox:"}) +      {:ok, activity} = +        CommonAPI.post(user, %{ +          status: "#2hu :firefox:", +          generator: %{type: "Application", name: "TestClient", url: "https://pleroma.social"} +        }) + +      # Ensure injected application data made it into the activity +      # as we don't have a Token to derive it from, otherwise it will +      # be nil and the test will pass +      assert %{ +               type: "Application", +               name: "TestClient", +               url: "https://pleroma.social" +             } == activity.object.data["generator"]        {:ok, modified} = Transmogrifier.prepare_outgoing(activity.data) @@ -213,6 +217,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        assert is_nil(modified["object"]["announcements"])        assert is_nil(modified["object"]["announcement_count"])        assert is_nil(modified["object"]["context_id"]) +      assert is_nil(modified["object"]["generator"])      end      test "it strips internal fields of article" do @@ -281,6 +286,21 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do        {:ok, _modified} = Transmogrifier.prepare_outgoing(activity.data)      end + +    test "custom emoji urls are URI encoded" do +      # :dinosaur: filename has a space -> dino walking.gif +      user = insert(:user) + +      {:ok, activity} = CommonAPI.post(user, %{status: "everybody do the dinosaur :dinosaur:"}) + +      {:ok, prepared} = Transmogrifier.prepare_outgoing(activity.data) + +      assert length(prepared["object"]["tag"]) == 1 + +      url = prepared["object"]["tag"] |> List.first() |> Map.get("icon") |> Map.get("url") + +      assert url == "http://localhost:4001/emoji/dino%20walking.gif" +    end    end    describe "user upgrade" do diff --git a/test/pleroma/web/activity_pub/utils_test.exs b/test/pleroma/web/activity_pub/utils_test.exs index be9cd7d13..ee3e1014e 100644 --- a/test/pleroma/web/activity_pub/utils_test.exs +++ b/test/pleroma/web/activity_pub/utils_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.UtilsTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity    alias Pleroma.Object    alias Pleroma.Repo @@ -165,7 +165,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do            }          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        {:ok, votes, object} = CommonAPI.vote(other_user, object, [0, 1])        assert Enum.sort(Utils.get_existing_votes(other_user.ap_id, object)) == Enum.sort(votes)      end @@ -183,7 +183,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do            }          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        {:ok, [vote], object} = CommonAPI.vote(other_user, object, [0])        {:ok, _activity} = CommonAPI.favorite(user, activity.id)        [fetched_vote] = Utils.get_existing_votes(other_user.ap_id, object) @@ -242,7 +242,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do      test "updates likes" do        user = insert(:user)        activity = insert(:note_activity) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert {:ok, updated_object} =                 Utils.update_element_in_object( @@ -302,7 +302,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do    describe "get_existing_like/2" do      test "fetches existing like" do        note_activity = insert(:note_activity) -      assert object = Object.normalize(note_activity) +      assert object = Object.normalize(note_activity, fetch: false)        user = insert(:user)        refute Utils.get_existing_like(user.ap_id, object) @@ -320,7 +320,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do      test "fetches existing announce" do        note_activity = insert(:note_activity) -      assert object = Object.normalize(note_activity) +      assert object = Object.normalize(note_activity, fetch: false)        actor = insert(:user)        {:ok, announce} = CommonAPI.repeat(note_activity.id, actor) @@ -412,7 +412,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do    describe "lazy_put_activity_defaults/2" do      test "returns map with id and published data" do        note_activity = insert(:note_activity) -      object = Object.normalize(note_activity) +      object = Object.normalize(note_activity, fetch: false)        res = Utils.lazy_put_activity_defaults(%{"context" => object.data["id"]})        assert res["context"] == object.data["id"]        assert res["context_id"] == object.id @@ -431,7 +431,7 @@ defmodule Pleroma.Web.ActivityPub.UtilsTest do      test "returns activity data with object" do        note_activity = insert(:note_activity) -      object = Object.normalize(note_activity) +      object = Object.normalize(note_activity, fetch: false)        res =          Utils.lazy_put_activity_defaults(%{ diff --git a/test/pleroma/web/activity_pub/views/object_view_test.exs b/test/pleroma/web/activity_pub/views/object_view_test.exs index f0389845d..923515dec 100644 --- a/test/pleroma/web/activity_pub/views/object_view_test.exs +++ b/test/pleroma/web/activity_pub/views/object_view_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.ObjectViewTest do @@ -24,7 +24,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectViewTest do    test "renders a note activity" do      note = insert(:note_activity) -    object = Object.normalize(note) +    object = Object.normalize(note, fetch: false)      result = ObjectView.render("object.json", %{object: note}) @@ -56,7 +56,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectViewTest do    test "renders a like activity" do      note = insert(:note_activity) -    object = Object.normalize(note) +    object = Object.normalize(note, fetch: false)      user = insert(:user)      {:ok, like_activity} = CommonAPI.favorite(user, note.id) @@ -70,7 +70,7 @@ defmodule Pleroma.Web.ActivityPub.ObjectViewTest do    test "renders an announce activity" do      note = insert(:note_activity) -    object = Object.normalize(note) +    object = Object.normalize(note, fetch: false)      user = insert(:user)      {:ok, announce_activity} = CommonAPI.repeat(note.id, user) diff --git a/test/pleroma/web/activity_pub/views/user_view_test.exs b/test/pleroma/web/activity_pub/views/user_view_test.exs index 98c7c9d09..f2de4d332 100644 --- a/test/pleroma/web/activity_pub/views/user_view_test.exs +++ b/test/pleroma/web/activity_pub/views/user_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.UserViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.User @@ -80,6 +80,12 @@ defmodule Pleroma.Web.ActivityPub.UserViewTest do      assert %{"invisible" => true} = UserView.render("service.json", %{user: user})    end +  test "renders AKAs" do +    akas = ["https://i.tusooa.xyz/users/test-pleroma"] +    user = insert(:user, also_known_as: akas) +    assert %{"alsoKnownAs" => ^akas} = UserView.render("user.json", %{user: user}) +  end +    describe "endpoints" do      test "local users have a usable endpoints structure" do        user = insert(:user) diff --git a/test/pleroma/web/activity_pub/visibility_test.exs b/test/pleroma/web/activity_pub/visibility_test.exs index 836d44994..23485225d 100644 --- a/test/pleroma/web/activity_pub/visibility_test.exs +++ b/test/pleroma/web/activity_pub/visibility_test.exs @@ -1,11 +1,12 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ActivityPub.VisibilityTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Activity +  alias Pleroma.Object    alias Pleroma.Web.ActivityPub.Visibility    alias Pleroma.Web.CommonAPI    import Pleroma.Factory @@ -107,7 +108,7 @@ defmodule Pleroma.Web.ActivityPub.VisibilityTest do      assert Visibility.is_list?(list)    end -  test "visible_for_user?", %{ +  test "visible_for_user? Activity", %{      public: public,      private: private,      direct: direct, @@ -149,17 +150,83 @@ defmodule Pleroma.Web.ActivityPub.VisibilityTest do      refute Visibility.visible_for_user?(private, unrelated)      refute Visibility.visible_for_user?(direct, unrelated) +    # Public and unlisted visible for unauthenticated + +    assert Visibility.visible_for_user?(public, nil) +    assert Visibility.visible_for_user?(unlisted, nil) +    refute Visibility.visible_for_user?(private, nil) +    refute Visibility.visible_for_user?(direct, nil) +      # Visible for a list member      assert Visibility.visible_for_user?(list, unrelated)    end +  test "visible_for_user? Object", %{ +    public: public, +    private: private, +    direct: direct, +    unlisted: unlisted, +    user: user, +    mentioned: mentioned, +    following: following, +    unrelated: unrelated, +    list: list +  } do +    public = Object.normalize(public) +    private = Object.normalize(private) +    unlisted = Object.normalize(unlisted) +    direct = Object.normalize(direct) +    list = Object.normalize(list) + +    # All visible to author + +    assert Visibility.visible_for_user?(public, user) +    assert Visibility.visible_for_user?(private, user) +    assert Visibility.visible_for_user?(unlisted, user) +    assert Visibility.visible_for_user?(direct, user) +    assert Visibility.visible_for_user?(list, user) + +    # All visible to a mentioned user + +    assert Visibility.visible_for_user?(public, mentioned) +    assert Visibility.visible_for_user?(private, mentioned) +    assert Visibility.visible_for_user?(unlisted, mentioned) +    assert Visibility.visible_for_user?(direct, mentioned) +    assert Visibility.visible_for_user?(list, mentioned) + +    # DM not visible for just follower + +    assert Visibility.visible_for_user?(public, following) +    assert Visibility.visible_for_user?(private, following) +    assert Visibility.visible_for_user?(unlisted, following) +    refute Visibility.visible_for_user?(direct, following) +    refute Visibility.visible_for_user?(list, following) + +    # Public and unlisted visible for unrelated user + +    assert Visibility.visible_for_user?(public, unrelated) +    assert Visibility.visible_for_user?(unlisted, unrelated) +    refute Visibility.visible_for_user?(private, unrelated) +    refute Visibility.visible_for_user?(direct, unrelated) + +    # Public and unlisted visible for unauthenticated + +    assert Visibility.visible_for_user?(public, nil) +    assert Visibility.visible_for_user?(unlisted, nil) +    refute Visibility.visible_for_user?(private, nil) +    refute Visibility.visible_for_user?(direct, nil) + +    # Visible for a list member +    # assert Visibility.visible_for_user?(list, unrelated) +  end +    test "doesn't die when the user doesn't exist",         %{           direct: direct,           user: user         } do      Repo.delete(user) -    Cachex.clear(:user_cache) +    Pleroma.User.invalidate_cache(user)      refute Visibility.is_private?(direct)    end diff --git a/test/pleroma/web/admin_api/controllers/admin_api_controller_test.exs b/test/pleroma/web/admin_api/controllers/admin_api_controller_test.exs index e50d1425b..8cd9f939b 100644 --- a/test/pleroma/web/admin_api/controllers/admin_api_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/admin_api_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do @@ -46,104 +46,47 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do      assert json_response(conn, 200)    end -  describe "with [:auth, :enforce_oauth_admin_scope_usage]," do -    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], true) +  test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope", +       %{admin: admin} do +    user = insert(:user) +    url = "/api/pleroma/admin/users/#{user.nickname}" -    test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope", -         %{admin: admin} do -      user = insert(:user) -      url = "/api/pleroma/admin/users/#{user.nickname}" - -      good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) -      good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) -      good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) - -      bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) -      bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) -      bad_token3 = nil - -      for good_token <- [good_token1, good_token2, good_token3] do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, good_token) -          |> get(url) - -        assert json_response(conn, 200) -      end - -      for good_token <- [good_token1, good_token2, good_token3] do -        conn = -          build_conn() -          |> assign(:user, nil) -          |> assign(:token, good_token) -          |> get(url) - -        assert json_response(conn, :forbidden) -      end - -      for bad_token <- [bad_token1, bad_token2, bad_token3] do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, bad_token) -          |> get(url) - -        assert json_response(conn, :forbidden) -      end +    good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) +    good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) +    good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) + +    bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) +    bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) +    bad_token3 = nil + +    for good_token <- [good_token1, good_token2, good_token3] do +      conn = +        build_conn() +        |> assign(:user, admin) +        |> assign(:token, good_token) +        |> get(url) + +      assert json_response(conn, 200)      end -  end -  describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do -    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false) +    for good_token <- [good_token1, good_token2, good_token3] do +      conn = +        build_conn() +        |> assign(:user, nil) +        |> assign(:token, good_token) +        |> get(url) -    test "GET /api/pleroma/admin/users/:nickname requires " <> -           "read:accounts or admin:read:accounts or broader scope", -         %{admin: admin} do -      user = insert(:user) -      url = "/api/pleroma/admin/users/#{user.nickname}" - -      good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) -      good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) -      good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) -      good_token4 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) -      good_token5 = insert(:oauth_token, user: admin, scopes: ["read"]) - -      good_tokens = [good_token1, good_token2, good_token3, good_token4, good_token5] - -      bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts:partial"]) -      bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) -      bad_token3 = nil - -      for good_token <- good_tokens do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, good_token) -          |> get(url) - -        assert json_response(conn, 200) -      end - -      for good_token <- good_tokens do -        conn = -          build_conn() -          |> assign(:user, nil) -          |> assign(:token, good_token) -          |> get(url) - -        assert json_response(conn, :forbidden) -      end - -      for bad_token <- [bad_token1, bad_token2, bad_token3] do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, bad_token) -          |> get(url) - -        assert json_response(conn, :forbidden) -      end +      assert json_response(conn, :forbidden) +    end + +    for bad_token <- [bad_token1, bad_token2, bad_token3] do +      conn = +        build_conn() +        |> assign(:user, admin) +        |> assign(:token, bad_token) +        |> get(url) + +      assert json_response(conn, :forbidden)      end    end @@ -405,13 +348,9 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do      setup do        user = insert(:user) -      date1 = (DateTime.to_unix(DateTime.utc_now()) + 2000) |> DateTime.from_unix!() -      date2 = (DateTime.to_unix(DateTime.utc_now()) + 1000) |> DateTime.from_unix!() -      date3 = (DateTime.to_unix(DateTime.utc_now()) + 3000) |> DateTime.from_unix!() - -      insert(:note_activity, user: user, published: date1) -      insert(:note_activity, user: user, published: date2) -      insert(:note_activity, user: user, published: date3) +      insert(:note_activity, user: user) +      insert(:note_activity, user: user) +      insert(:note_activity, user: user)        %{user: user}      end @@ -419,13 +358,22 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do      test "renders user's statuses", %{conn: conn, user: user} do        conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses") -      assert json_response(conn, 200) |> length() == 3 +      assert %{"total" => 3, "activities" => activities} = json_response(conn, 200) +      assert length(activities) == 3      end -    test "renders user's statuses with a limit", %{conn: conn, user: user} do -      conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses?page_size=2") +    test "renders user's statuses with pagination", %{conn: conn, user: user} do +      %{"total" => 3, "activities" => [activity1]} = +        conn +        |> get("/api/pleroma/admin/users/#{user.nickname}/statuses?page_size=1&page=1") +        |> json_response(200) -      assert json_response(conn, 200) |> length() == 2 +      %{"total" => 3, "activities" => [activity2]} = +        conn +        |> get("/api/pleroma/admin/users/#{user.nickname}/statuses?page_size=1&page=2") +        |> json_response(200) + +      refute activity1 == activity2      end      test "doesn't return private statuses by default", %{conn: conn, user: user} do @@ -433,9 +381,12 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"}) -      conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses") +      %{"total" => 4, "activities" => activities} = +        conn +        |> get("/api/pleroma/admin/users/#{user.nickname}/statuses") +        |> json_response(200) -      assert json_response(conn, 200) |> length() == 4 +      assert length(activities) == 4      end      test "returns private statuses with godmode on", %{conn: conn, user: user} do @@ -443,9 +394,12 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        {:ok, _public_status} = CommonAPI.post(user, %{status: "public", visibility: "public"}) -      conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}/statuses?godmode=true") +      %{"total" => 5, "activities" => activities} = +        conn +        |> get("/api/pleroma/admin/users/#{user.nickname}/statuses?godmode=true") +        |> json_response(200) -      assert json_response(conn, 200) |> length() == 5 +      assert length(activities) == 5      end      test "excludes reblogs by default", %{conn: conn, user: user} do @@ -453,13 +407,17 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        {:ok, activity} = CommonAPI.post(user, %{status: "."})        {:ok, %Activity{}} = CommonAPI.repeat(activity.id, other_user) -      conn_res = get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses") -      assert json_response(conn_res, 200) |> length() == 0 - -      conn_res = -        get(conn, "/api/pleroma/admin/users/#{other_user.nickname}/statuses?with_reblogs=true") +      assert %{"total" => 0, "activities" => []} == +               conn +               |> get("/api/pleroma/admin/users/#{other_user.nickname}/statuses") +               |> json_response(200) -      assert json_response(conn_res, 200) |> length() == 1 +      assert %{"total" => 1, "activities" => [_]} = +               conn +               |> get( +                 "/api/pleroma/admin/users/#{other_user.nickname}/statuses?with_reblogs=true" +               ) +               |> json_response(200)      end    end @@ -849,42 +807,39 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        insert_pair(:note_activity, user: user)        activity = insert(:note_activity, user: user2) -      ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses") - -      response = json_response(ret_conn, 200) - -      assert length(response) == 2 - -      ret_conn = get(conn, "/api/pleroma/admin/instances/test.com/statuses") +      %{"total" => 2, "activities" => activities} = +        conn |> get("/api/pleroma/admin/instances/archae.me/statuses") |> json_response(200) -      response = json_response(ret_conn, 200) +      assert length(activities) == 2 -      assert length(response) == 1 +      %{"total" => 1, "activities" => [_]} = +        conn |> get("/api/pleroma/admin/instances/test.com/statuses") |> json_response(200) -      ret_conn = get(conn, "/api/pleroma/admin/instances/nonexistent.com/statuses") +      %{"total" => 0, "activities" => []} = +        conn |> get("/api/pleroma/admin/instances/nonexistent.com/statuses") |> json_response(200) -      response = json_response(ret_conn, 200) +      CommonAPI.repeat(activity.id, user) -      assert Enum.empty?(response) +      %{"total" => 2, "activities" => activities} = +        conn |> get("/api/pleroma/admin/instances/archae.me/statuses") |> json_response(200) -      CommonAPI.repeat(activity.id, user) +      assert length(activities) == 2 -      ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses") -      response = json_response(ret_conn, 200) -      assert length(response) == 2 +      %{"total" => 3, "activities" => activities} = +        conn +        |> get("/api/pleroma/admin/instances/archae.me/statuses?with_reblogs=true") +        |> json_response(200) -      ret_conn = get(conn, "/api/pleroma/admin/instances/archae.me/statuses?with_reblogs=true") -      response = json_response(ret_conn, 200) -      assert length(response) == 3 +      assert length(activities) == 3      end    end    describe "PATCH /confirm_email" do      test "it confirms emails of two users", %{conn: conn, admin: admin} do -      [first_user, second_user] = insert_pair(:user, confirmation_pending: true) +      [first_user, second_user] = insert_pair(:user, is_confirmed: false) -      assert first_user.confirmation_pending == true -      assert second_user.confirmation_pending == true +      refute first_user.is_confirmed +      refute second_user.is_confirmed        ret_conn =          patch(conn, "/api/pleroma/admin/users/confirm_email", %{ @@ -896,8 +851,11 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do        assert ret_conn.status == 200 -      assert first_user.confirmation_pending == true -      assert second_user.confirmation_pending == true +      first_user = User.get_by_id(first_user.id) +      second_user = User.get_by_id(second_user.id) + +      assert first_user.is_confirmed +      assert second_user.is_confirmed        log_entry = Repo.one(ModerationLog) @@ -910,7 +868,7 @@ defmodule Pleroma.Web.AdminAPI.AdminAPIControllerTest do    describe "PATCH /resend_confirmation_email" do      test "it resend emails for two users", %{conn: conn, admin: admin} do -      [first_user, second_user] = insert_pair(:user, confirmation_pending: true) +      [first_user, second_user] = insert_pair(:user, is_confirmed: false)        ret_conn =          patch(conn, "/api/pleroma/admin/users/resend_confirmation_email", %{ diff --git a/test/pleroma/web/admin_api/controllers/chat_controller_test.exs b/test/pleroma/web/admin_api/controllers/chat_controller_test.exs index 5aefa1e60..0e8f7beef 100644 --- a/test/pleroma/web/admin_api/controllers/chat_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/chat_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.ChatControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory @@ -36,7 +36,7 @@ defmodule Pleroma.Web.AdminAPI.ChatControllerTest do        {:ok, message} =          CommonAPI.post_chat_message(user, recipient, "Hello darkness my old friend") -      object = Object.normalize(message, false) +      object = Object.normalize(message, fetch: false)        chat = Chat.get(user.id, recipient.ap_id)        recipient_chat = Chat.get(recipient.id, user.ap_id) @@ -143,7 +143,7 @@ defmodule Pleroma.Web.AdminAPI.ChatControllerTest do        recipient = insert(:user)        {:ok, message} = CommonAPI.post_chat_message(user, recipient, "Yo") -      object = Object.normalize(message, false) +      object = Object.normalize(message, fetch: false)        chat = Chat.get(user.id, recipient.ap_id)        cm_ref = MessageReference.for_chat_and_object(chat, object) @@ -183,7 +183,7 @@ defmodule Pleroma.Web.AdminAPI.ChatControllerTest do        recipient = insert(:user)        {:ok, message} = CommonAPI.post_chat_message(user, recipient, "Yo") -      object = Object.normalize(message, false) +      object = Object.normalize(message, fetch: false)        chat = Chat.get(user.id, recipient.ap_id)        cm_ref = MessageReference.for_chat_and_object(chat, object) diff --git a/test/pleroma/web/admin_api/controllers/config_controller_test.exs b/test/pleroma/web/admin_api/controllers/config_controller_test.exs index e6b203e74..c39c1b1e1 100644 --- a/test/pleroma/web/admin_api/controllers/config_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/config_controller_test.exs @@ -1,14 +1,13 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.ConfigControllerTest do -  use Pleroma.Web.ConnCase, async: true +  use Pleroma.Web.ConnCase    import ExUnit.CaptureLog    import Pleroma.Factory -  alias Pleroma.Config    alias Pleroma.ConfigDB    setup do @@ -27,12 +26,12 @@ defmodule Pleroma.Web.AdminAPI.ConfigControllerTest do      setup do: clear_config(:configurable_from_database, true)      test "when configuration from database is off", %{conn: conn} do -      Config.put(:configurable_from_database, false) +      clear_config(:configurable_from_database, false)        conn = get(conn, "/api/pleroma/admin/config")        assert json_response_and_validate_schema(conn, 400) ==                 %{ -                 "error" => "To use this endpoint you need to enable configuration from database." +                 "error" => "You must enable configurable_from_database in your config file."                 }      end @@ -171,7 +170,7 @@ defmodule Pleroma.Web.AdminAPI.ConfigControllerTest do        |> post("/api/pleroma/admin/config", %{"configs" => []})      assert json_response_and_validate_schema(conn, 400) == -             %{"error" => "To use this endpoint you need to enable configuration from database."} +             %{"error" => "You must enable configurable_from_database in your config file."}    end    describe "POST /api/pleroma/admin/config" do @@ -410,8 +409,7 @@ defmodule Pleroma.Web.AdminAPI.ConfigControllerTest do      end      test "saving config which need pleroma reboot", %{conn: conn} do -      chat = Config.get(:chat) -      on_exit(fn -> Config.put(:chat, chat) end) +      clear_config([:chat, :enabled], true)        assert conn               |> put_req_header("content-type", "application/json") @@ -456,8 +454,7 @@ defmodule Pleroma.Web.AdminAPI.ConfigControllerTest do      end      test "update setting which need reboot, don't change reboot flag until reboot", %{conn: conn} do -      chat = Config.get(:chat) -      on_exit(fn -> Config.put(:chat, chat) end) +      clear_config([:chat, :enabled], true)        assert conn               |> put_req_header("content-type", "application/json") @@ -1413,6 +1410,82 @@ defmodule Pleroma.Web.AdminAPI.ConfigControllerTest do                 "need_reboot" => false               }      end + +    test "custom instance thumbnail", %{conn: conn} do +      clear_config([:instance]) + +      params = %{ +        "group" => ":pleroma", +        "key" => ":instance", +        "value" => [ +          %{ +            "tuple" => [ +              ":instance_thumbnail", +              "https://example.com/media/new_thumbnail.jpg" +            ] +          } +        ] +      } + +      res = +        assert conn +               |> put_req_header("content-type", "application/json") +               |> post("/api/pleroma/admin/config", %{"configs" => [params]}) +               |> json_response_and_validate_schema(200) + +      assert res == %{ +               "configs" => [ +                 %{ +                   "db" => [":instance_thumbnail"], +                   "group" => ":pleroma", +                   "key" => ":instance", +                   "value" => params["value"] +                 } +               ], +               "need_reboot" => false +             } + +      _res = +        assert conn +               |> get("/api/v1/instance") +               |> json_response_and_validate_schema(200) + +      assert res = %{"thumbnail" => "https://example.com/media/new_thumbnail.jpg"} +    end + +    test "Concurrent Limiter", %{conn: conn} do +      clear_config([ConcurrentLimiter]) + +      params = %{ +        "group" => ":pleroma", +        "key" => "ConcurrentLimiter", +        "value" => [ +          %{ +            "tuple" => [ +              "Pleroma.Web.RichMedia.Helpers", +              [ +                %{"tuple" => [":max_running", 6]}, +                %{"tuple" => [":max_waiting", 6]} +              ] +            ] +          }, +          %{ +            "tuple" => [ +              "Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicy", +              [ +                %{"tuple" => [":max_running", 7]}, +                %{"tuple" => [":max_waiting", 7]} +              ] +            ] +          } +        ] +      } + +      assert conn +             |> put_req_header("content-type", "application/json") +             |> post("/api/pleroma/admin/config", %{"configs" => [params]}) +             |> json_response_and_validate_schema(200) +    end    end    describe "GET /api/pleroma/admin/config/descriptions" do diff --git a/test/pleroma/web/admin_api/controllers/frontend_controller_test.exs b/test/pleroma/web/admin_api/controllers/frontend_controller_test.exs index 94873f6db..bc827cc12 100644 --- a/test/pleroma/web/admin_api/controllers/frontend_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/frontend_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.FrontendControllerTest do diff --git a/test/pleroma/web/admin_api/controllers/instance_document_controller_test.exs b/test/pleroma/web/admin_api/controllers/instance_document_controller_test.exs index ce867dd0e..e100f6929 100644 --- a/test/pleroma/web/admin_api/controllers/instance_document_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/instance_document_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.InstanceDocumentControllerTest do diff --git a/test/pleroma/web/admin_api/controllers/invite_controller_test.exs b/test/pleroma/web/admin_api/controllers/invite_controller_test.exs index ab186c5e7..6366061c8 100644 --- a/test/pleroma/web/admin_api/controllers/invite_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/invite_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.InviteControllerTest do @@ -7,7 +7,6 @@ defmodule Pleroma.Web.AdminAPI.InviteControllerTest do    import Pleroma.Factory -  alias Pleroma.Config    alias Pleroma.Repo    alias Pleroma.UserInviteToken @@ -119,8 +118,8 @@ defmodule Pleroma.Web.AdminAPI.InviteControllerTest do      setup do: clear_config([:instance, :invites_enabled])      test "it returns 500 if `invites_enabled` is not enabled", %{conn: conn} do -      Config.put([:instance, :registrations_open], false) -      Config.put([:instance, :invites_enabled], false) +      clear_config([:instance, :registrations_open], false) +      clear_config([:instance, :invites_enabled], false)        conn =          conn @@ -138,8 +137,8 @@ defmodule Pleroma.Web.AdminAPI.InviteControllerTest do      end      test "it returns 500 if `registrations_open` is enabled", %{conn: conn} do -      Config.put([:instance, :registrations_open], true) -      Config.put([:instance, :invites_enabled], true) +      clear_config([:instance, :registrations_open], true) +      clear_config([:instance, :invites_enabled], true)        conn =          conn diff --git a/test/pleroma/web/admin_api/controllers/media_proxy_cache_controller_test.exs b/test/pleroma/web/admin_api/controllers/media_proxy_cache_controller_test.exs index f243d1fb2..5d872901e 100644 --- a/test/pleroma/web/admin_api/controllers/media_proxy_cache_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/media_proxy_cache_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.MediaProxyCacheControllerTest do @@ -13,10 +13,6 @@ defmodule Pleroma.Web.AdminAPI.MediaProxyCacheControllerTest do    setup do: clear_config([:media_proxy])    setup do -    on_exit(fn -> Cachex.clear(:banned_urls_cache) end) -  end - -  setup do      admin = insert(:user, is_admin: true)      token = insert(:oauth_admin_token, user: admin) @@ -25,9 +21,9 @@ defmodule Pleroma.Web.AdminAPI.MediaProxyCacheControllerTest do        |> assign(:user, admin)        |> assign(:token, token) -    Config.put([:media_proxy, :enabled], true) -    Config.put([:media_proxy, :invalidation, :enabled], true) -    Config.put([:media_proxy, :invalidation, :provider], MediaProxy.Invalidation.Script) +    clear_config([:media_proxy, :enabled], true) +    clear_config([:media_proxy, :invalidation, :enabled], true) +    clear_config([:media_proxy, :invalidation, :provider], MediaProxy.Invalidation.Script)      {:ok, %{admin: admin, token: token, conn: conn}}    end diff --git a/test/pleroma/web/admin_api/controllers/o_auth_app_controller_test.exs b/test/pleroma/web/admin_api/controllers/o_auth_app_controller_test.exs index f388375d1..8c7b63f34 100644 --- a/test/pleroma/web/admin_api/controllers/o_auth_app_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/o_auth_app_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.OAuthAppControllerTest do diff --git a/test/pleroma/web/admin_api/controllers/relay_controller_test.exs b/test/pleroma/web/admin_api/controllers/relay_controller_test.exs index 379067a62..11a480cc0 100644 --- a/test/pleroma/web/admin_api/controllers/relay_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/relay_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.RelayControllerTest do diff --git a/test/pleroma/web/admin_api/controllers/report_controller_test.exs b/test/pleroma/web/admin_api/controllers/report_controller_test.exs index cbfc2e7b0..6a2986b5f 100644 --- a/test/pleroma/web/admin_api/controllers/report_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/report_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.ReportControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/web/admin_api/controllers/status_controller_test.exs b/test/pleroma/web/admin_api/controllers/status_controller_test.exs index a18ef9e4b..3fdf23ba2 100644 --- a/test/pleroma/web/admin_api/controllers/status_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/status_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.StatusControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory @@ -47,8 +47,8 @@ defmodule Pleroma.Web.AdminAPI.StatusControllerTest do        assert account["id"] == actor.id        assert account["nickname"] == actor.nickname -      assert account["deactivated"] == actor.deactivated -      assert account["confirmation_pending"] == actor.confirmation_pending +      assert account["is_active"] == actor.is_active +      assert account["is_confirmed"] == actor.is_confirmed      end    end diff --git a/test/pleroma/web/admin_api/controllers/user_controller_test.exs b/test/pleroma/web/admin_api/controllers/user_controller_test.exs index 5705306c7..31319b5e5 100644 --- a/test/pleroma/web/admin_api/controllers/user_controller_test.exs +++ b/test/pleroma/web/admin_api/controllers/user_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.UserControllerTest do @@ -44,107 +44,50 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do      conn = get(build_conn(), "/api/pleroma/admin/users/#{user.nickname}?admin_token=password123") -    assert json_response(conn, 200) +    assert json_response_and_validate_schema(conn, 200)    end -  describe "with [:auth, :enforce_oauth_admin_scope_usage]," do -    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], true) - -    test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope", -         %{admin: admin} do -      user = insert(:user) -      url = "/api/pleroma/admin/users/#{user.nickname}" - -      good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) -      good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) -      good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) - -      bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) -      bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) -      bad_token3 = nil - -      for good_token <- [good_token1, good_token2, good_token3] do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, good_token) -          |> get(url) - -        assert json_response(conn, 200) -      end +  test "GET /api/pleroma/admin/users/:nickname requires admin:read:accounts or broader scope", +       %{admin: admin} do +    user = insert(:user) +    url = "/api/pleroma/admin/users/#{user.nickname}" -      for good_token <- [good_token1, good_token2, good_token3] do -        conn = -          build_conn() -          |> assign(:user, nil) -          |> assign(:token, good_token) -          |> get(url) +    good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) +    good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) +    good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) -        assert json_response(conn, :forbidden) -      end +    bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) +    bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) +    bad_token3 = nil -      for bad_token <- [bad_token1, bad_token2, bad_token3] do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, bad_token) -          |> get(url) +    for good_token <- [good_token1, good_token2, good_token3] do +      conn = +        build_conn() +        |> assign(:user, admin) +        |> assign(:token, good_token) +        |> get(url) -        assert json_response(conn, :forbidden) -      end +      assert json_response_and_validate_schema(conn, 200)      end -  end - -  describe "unless [:auth, :enforce_oauth_admin_scope_usage]," do -    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false) - -    test "GET /api/pleroma/admin/users/:nickname requires " <> -           "read:accounts or admin:read:accounts or broader scope", -         %{admin: admin} do -      user = insert(:user) -      url = "/api/pleroma/admin/users/#{user.nickname}" - -      good_token1 = insert(:oauth_token, user: admin, scopes: ["admin"]) -      good_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read"]) -      good_token3 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts"]) -      good_token4 = insert(:oauth_token, user: admin, scopes: ["read:accounts"]) -      good_token5 = insert(:oauth_token, user: admin, scopes: ["read"]) - -      good_tokens = [good_token1, good_token2, good_token3, good_token4, good_token5] - -      bad_token1 = insert(:oauth_token, user: admin, scopes: ["read:accounts:partial"]) -      bad_token2 = insert(:oauth_token, user: admin, scopes: ["admin:read:accounts:partial"]) -      bad_token3 = nil -      for good_token <- good_tokens do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, good_token) -          |> get(url) - -        assert json_response(conn, 200) -      end - -      for good_token <- good_tokens do -        conn = -          build_conn() -          |> assign(:user, nil) -          |> assign(:token, good_token) -          |> get(url) +    for good_token <- [good_token1, good_token2, good_token3] do +      conn = +        build_conn() +        |> assign(:user, nil) +        |> assign(:token, good_token) +        |> get(url) -        assert json_response(conn, :forbidden) -      end +      assert json_response(conn, :forbidden) +    end -      for bad_token <- [bad_token1, bad_token2, bad_token3] do -        conn = -          build_conn() -          |> assign(:user, admin) -          |> assign(:token, bad_token) -          |> get(url) +    for bad_token <- [bad_token1, bad_token2, bad_token3] do +      conn = +        build_conn() +        |> assign(:user, admin) +        |> assign(:token, bad_token) +        |> get(url) -        assert json_response(conn, :forbidden) -      end +      assert json_response_and_validate_schema(conn, :forbidden)      end    end @@ -169,7 +112,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        assert user.note_count == 1        assert user.follower_count == 1        assert user.following_count == 1 -      refute user.deactivated +      assert user.is_active        with_mock Pleroma.Web.Federator,          publish: fn _ -> nil end, @@ -181,17 +124,17 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do          ObanHelpers.perform_all() -        assert User.get_by_nickname(user.nickname).deactivated +        refute User.get_by_nickname(user.nickname).is_active          log_entry = Repo.one(ModerationLog)          assert ModerationLog.get_log_entry_message(log_entry) ==                   "@#{admin.nickname} deleted users: @#{user.nickname}" -        assert json_response(conn, 200) == [user.nickname] +        assert json_response_and_validate_schema(conn, 200) == [user.nickname]          user = Repo.get(User, user.id) -        assert user.deactivated +        refute user.is_active          assert user.avatar == %{}          assert user.banner == %{} @@ -209,28 +152,30 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        user_one = insert(:user)        user_two = insert(:user) -      conn = +      response =          conn          |> put_req_header("accept", "application/json") +        |> put_req_header("content-type", "application/json")          |> delete("/api/pleroma/admin/users", %{            nicknames: [user_one.nickname, user_two.nickname]          }) +        |> json_response_and_validate_schema(200)        log_entry = Repo.one(ModerationLog)        assert ModerationLog.get_log_entry_message(log_entry) ==                 "@#{admin.nickname} deleted users: @#{user_one.nickname}, @#{user_two.nickname}" -      response = json_response(conn, 200)        assert response -- [user_one.nickname, user_two.nickname] == []      end    end    describe "/api/pleroma/admin/users" do      test "Create", %{conn: conn} do -      conn = +      response =          conn          |> put_req_header("accept", "application/json") +        |> put_req_header("content-type", "application/json")          |> post("/api/pleroma/admin/users", %{            "users" => [              %{ @@ -245,8 +190,9 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do              }            ]          }) +        |> json_response_and_validate_schema(200) +        |> Enum.map(&Map.get(&1, "type")) -      response = json_response(conn, 200) |> Enum.map(&Map.get(&1, "type"))        assert response == ["success", "success"]        log_entry = Repo.one(ModerationLog) @@ -260,6 +206,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn =          conn          |> put_req_header("accept", "application/json") +        |> put_req_header("content-type", "application/json")          |> post("/api/pleroma/admin/users", %{            "users" => [              %{ @@ -270,7 +217,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do            ]          }) -      assert json_response(conn, 409) == [ +      assert json_response_and_validate_schema(conn, 409) == [                 %{                   "code" => 409,                   "data" => %{ @@ -289,6 +236,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn =          conn          |> put_req_header("accept", "application/json") +        |> put_req_header("content-type", "application/json")          |> post("/api/pleroma/admin/users", %{            "users" => [              %{ @@ -299,7 +247,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do            ]          }) -      assert json_response(conn, 409) == [ +      assert json_response_and_validate_schema(conn, 409) == [                 %{                   "code" => 409,                   "data" => %{ @@ -318,6 +266,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn =          conn          |> put_req_header("accept", "application/json") +        |> put_req_header("content-type", "application/json")          |> post("/api/pleroma/admin/users", %{            "users" => [              %{ @@ -333,7 +282,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do            ]          }) -      assert json_response(conn, 409) == [ +      assert json_response_and_validate_schema(conn, 409) == [                 %{                   "code" => 409,                   "data" => %{ @@ -364,7 +313,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}") -      assert user_response(user) == json_response(conn, 200) +      assert user_response(user) == json_response_and_validate_schema(conn, 200)      end      test "when the user doesn't exist", %{conn: conn} do @@ -372,7 +321,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users/#{user.nickname}") -      assert %{"error" => "Not found"} == json_response(conn, 404) +      assert %{"error" => "Not found"} == json_response_and_validate_schema(conn, 404)      end    end @@ -383,6 +332,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn        |> put_req_header("accept", "application/json") +      |> put_req_header("content-type", "application/json")        |> post("/api/pleroma/admin/users/follow", %{          "follower" => follower.nickname,          "followed" => user.nickname @@ -409,6 +359,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn        |> put_req_header("accept", "application/json") +      |> put_req_header("content-type", "application/json")        |> post("/api/pleroma/admin/users/unfollow", %{          "follower" => follower.nickname,          "followed" => user.nickname @@ -429,7 +380,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do    describe "GET /api/pleroma/admin/users" do      test "renders users array for the first page", %{conn: conn, admin: admin} do        user = insert(:user, local: false, tags: ["foo", "bar"]) -      user2 = insert(:user, approval_pending: true, registration_reason: "I'm a chill dude") +      user2 = insert(:user, is_approved: false, registration_reason: "I'm a chill dude")        conn = get(conn, "/api/pleroma/admin/users?page=1") @@ -444,7 +395,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do              user2,              %{                "local" => true, -              "approval_pending" => true, +              "is_approved" => false,                "registration_reason" => "I'm a chill dude",                "actor_type" => "Person"              } @@ -452,7 +403,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do          ]          |> Enum.sort_by(& &1["nickname"]) -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 3,                 "page_size" => 50,                 "users" => users @@ -467,7 +418,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        assert %{"count" => 26, "page_size" => 10, "users" => users1} =                 conn                 |> get("/api/pleroma/admin/users?page=1&filters=", %{page_size: "10"}) -               |> json_response(200) +               |> json_response_and_validate_schema(200)        assert Enum.count(users1) == 10        assert service1 not in users1 @@ -475,7 +426,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        assert %{"count" => 26, "page_size" => 10, "users" => users2} =                 conn                 |> get("/api/pleroma/admin/users?page=2&filters=", %{page_size: "10"}) -               |> json_response(200) +               |> json_response_and_validate_schema(200)        assert Enum.count(users2) == 10        assert service1 not in users2 @@ -483,7 +434,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        assert %{"count" => 26, "page_size" => 10, "users" => users3} =                 conn                 |> get("/api/pleroma/admin/users?page=3&filters=", %{page_size: "10"}) -               |> json_response(200) +               |> json_response_and_validate_schema(200)        assert Enum.count(users3) == 6        assert service1 not in users3 @@ -494,7 +445,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users?page=2") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 2,                 "page_size" => 50,                 "users" => [] @@ -506,7 +457,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users?query=bo") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [user_response(user, %{"local" => true})] @@ -519,7 +470,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users?query=domain.com") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [user_response(user)] @@ -532,7 +483,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users?query=nickname@domain.com") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [user_response(user)] @@ -545,7 +496,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users?name=display") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [user_response(user)] @@ -558,7 +509,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users?email=email@example.com") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [user_response(user)] @@ -571,7 +522,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn1 = get(conn, "/api/pleroma/admin/users?query=a&page_size=1&page=1") -      assert json_response(conn1, 200) == %{ +      assert json_response_and_validate_schema(conn1, 200) == %{                 "count" => 2,                 "page_size" => 1,                 "users" => [user_response(user)] @@ -579,7 +530,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn2 = get(conn, "/api/pleroma/admin/users?query=a&page_size=1&page=2") -      assert json_response(conn2, 200) == %{ +      assert json_response_and_validate_schema(conn2, 200) == %{                 "count" => 2,                 "page_size" => 1,                 "users" => [user_response(user2)] @@ -599,7 +550,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do          |> assign(:token, token)          |> get("/api/pleroma/admin/users?query=bo&filters=local") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [user_response(user)] @@ -621,13 +572,13 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do              "roles" => %{"admin" => true, "moderator" => false}            }),            user_response(old_admin, %{ -            "deactivated" => false, +            "is_active" => true,              "roles" => %{"admin" => true, "moderator" => false}            })          ]          |> Enum.sort_by(& &1["nickname"]) -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 3,                 "page_size" => 50,                 "users" => users @@ -635,22 +586,22 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do      end      test "only unconfirmed users", %{conn: conn} do -      sad_user = insert(:user, nickname: "sadboy", confirmation_pending: true) -      old_user = insert(:user, nickname: "oldboy", confirmation_pending: true) +      sad_user = insert(:user, nickname: "sadboy", is_confirmed: false) +      old_user = insert(:user, nickname: "oldboy", is_confirmed: false) -      insert(:user, nickname: "happyboy", approval_pending: false) -      insert(:user, confirmation_pending: false) +      insert(:user, nickname: "happyboy", is_approved: true) +      insert(:user, is_confirmed: true)        result =          conn          |> get("/api/pleroma/admin/users?filters=unconfirmed") -        |> json_response(200) +        |> json_response_and_validate_schema(200)        users =          Enum.map([old_user, sad_user], fn user ->            user_response(user, %{ -            "confirmation_pending" => true, -            "approval_pending" => false +            "is_confirmed" => false, +            "is_approved" => true            })          end)          |> Enum.sort_by(& &1["nickname"]) @@ -662,22 +613,22 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        user =          insert(:user,            nickname: "sadboy", -          approval_pending: true, +          is_approved: false,            registration_reason: "Plz let me in!"          ) -      insert(:user, nickname: "happyboy", approval_pending: false) +      insert(:user, nickname: "happyboy", is_approved: true)        conn = get(conn, "/api/pleroma/admin/users?filters=need_approval")        users = [          user_response(            user, -          %{"approval_pending" => true, "registration_reason" => "Plz let me in!"} +          %{"is_approved" => false, "registration_reason" => "Plz let me in!"}          )        ] -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => users @@ -694,17 +645,17 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        users =          [            user_response(admin, %{ -            "deactivated" => false, +            "is_active" => true,              "roles" => %{"admin" => true, "moderator" => false}            }),            user_response(second_admin, %{ -            "deactivated" => false, +            "is_active" => true,              "roles" => %{"admin" => true, "moderator" => false}            })          ]          |> Enum.sort_by(& &1["nickname"]) -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 2,                 "page_size" => 50,                 "users" => users @@ -718,12 +669,12 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users?filters=is_moderator") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [                   user_response(moderator, %{ -                   "deactivated" => false, +                   "is_active" => true,                     "roles" => %{"admin" => false, "moderator" => true}                   })                 ] @@ -739,8 +690,8 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        response =          conn -        |> get(user_path(conn, :list), %{actor_types: ["Person"]}) -        |> json_response(200) +        |> get(user_path(conn, :index), %{actor_types: ["Person"]}) +        |> json_response_and_validate_schema(200)        users =          [ @@ -762,8 +713,8 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        response =          conn -        |> get(user_path(conn, :list), %{actor_types: ["Person", "Service"]}) -        |> json_response(200) +        |> get(user_path(conn, :index), %{actor_types: ["Person", "Service"]}) +        |> json_response_and_validate_schema(200)        users =          [ @@ -785,8 +736,8 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        response =          conn -        |> get(user_path(conn, :list), %{actor_types: ["Service"]}) -        |> json_response(200) +        |> get(user_path(conn, :index), %{actor_types: ["Service"]}) +        |> json_response_and_validate_schema(200)        users = [user_response(user_service, %{"actor_type" => "Service"})] @@ -808,7 +759,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do          ]          |> Enum.sort_by(& &1["nickname"]) -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 2,                 "page_size" => 50,                 "users" => users @@ -816,8 +767,8 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do      end      test "`active` filters out users pending approval", %{token: token} do -      insert(:user, approval_pending: true) -      %{id: user_id} = insert(:user, approval_pending: false) +      insert(:user, is_approved: false) +      %{id: user_id} = insert(:user, is_approved: true)        %{id: admin_id} = token.user        conn = @@ -833,16 +784,16 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do                   %{"id" => ^admin_id},                   %{"id" => ^user_id}                 ] -             } = json_response(conn, 200) +             } = json_response_and_validate_schema(conn, 200)      end      test "it works with multiple filters" do        admin = insert(:user, nickname: "john", is_admin: true)        token = insert(:oauth_admin_token, user: admin) -      user = insert(:user, nickname: "bob", local: false, deactivated: true) +      user = insert(:user, nickname: "bob", local: false, is_active: false) -      insert(:user, nickname: "ken", local: true, deactivated: true) -      insert(:user, nickname: "bobb", local: false, deactivated: false) +      insert(:user, nickname: "ken", local: true, is_active: false) +      insert(:user, nickname: "bobb", local: false, is_active: true)        conn =          build_conn() @@ -850,7 +801,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do          |> assign(:token, token)          |> get("/api/pleroma/admin/users?filters=deactivated,external") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [user_response(user)] @@ -862,7 +813,7 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do        conn = get(conn, "/api/pleroma/admin/users") -      assert json_response(conn, 200) == %{ +      assert json_response_and_validate_schema(conn, 200) == %{                 "count" => 1,                 "page_size" => 50,                 "users" => [ @@ -873,18 +824,19 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do    end    test "PATCH /api/pleroma/admin/users/activate", %{admin: admin, conn: conn} do -    user_one = insert(:user, deactivated: true) -    user_two = insert(:user, deactivated: true) +    user_one = insert(:user, is_active: false) +    user_two = insert(:user, is_active: false)      conn = -      patch( -        conn, +      conn +      |> put_req_header("content-type", "application/json") +      |> patch(          "/api/pleroma/admin/users/activate",          %{nicknames: [user_one.nickname, user_two.nickname]}        ) -    response = json_response(conn, 200) -    assert Enum.map(response["users"], & &1["deactivated"]) == [false, false] +    response = json_response_and_validate_schema(conn, 200) +    assert Enum.map(response["users"], & &1["is_active"]) == [true, true]      log_entry = Repo.one(ModerationLog) @@ -893,18 +845,19 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do    end    test "PATCH /api/pleroma/admin/users/deactivate", %{admin: admin, conn: conn} do -    user_one = insert(:user, deactivated: false) -    user_two = insert(:user, deactivated: false) +    user_one = insert(:user, is_active: true) +    user_two = insert(:user, is_active: true)      conn = -      patch( -        conn, +      conn +      |> put_req_header("content-type", "application/json") +      |> patch(          "/api/pleroma/admin/users/deactivate",          %{nicknames: [user_one.nickname, user_two.nickname]}        ) -    response = json_response(conn, 200) -    assert Enum.map(response["users"], & &1["deactivated"]) == [true, true] +    response = json_response_and_validate_schema(conn, 200) +    assert Enum.map(response["users"], & &1["is_active"]) == [false, false]      log_entry = Repo.one(ModerationLog) @@ -913,18 +866,19 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do    end    test "PATCH /api/pleroma/admin/users/approve", %{admin: admin, conn: conn} do -    user_one = insert(:user, approval_pending: true) -    user_two = insert(:user, approval_pending: true) +    user_one = insert(:user, is_approved: false) +    user_two = insert(:user, is_approved: false)      conn = -      patch( -        conn, +      conn +      |> put_req_header("content-type", "application/json") +      |> patch(          "/api/pleroma/admin/users/approve",          %{nicknames: [user_one.nickname, user_two.nickname]}        ) -    response = json_response(conn, 200) -    assert Enum.map(response["users"], & &1["approval_pending"]) == [false, false] +    response = json_response_and_validate_schema(conn, 200) +    assert Enum.map(response["users"], & &1["is_approved"]) == [true, true]      log_entry = Repo.one(ModerationLog) @@ -935,12 +889,15 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do    test "PATCH /api/pleroma/admin/users/:nickname/toggle_activation", %{admin: admin, conn: conn} do      user = insert(:user) -    conn = patch(conn, "/api/pleroma/admin/users/#{user.nickname}/toggle_activation") +    conn = +      conn +      |> put_req_header("content-type", "application/json") +      |> patch("/api/pleroma/admin/users/#{user.nickname}/toggle_activation") -    assert json_response(conn, 200) == +    assert json_response_and_validate_schema(conn, 200) ==               user_response(                 user, -               %{"deactivated" => !user.deactivated} +               %{"is_active" => !user.is_active}               )      log_entry = Repo.one(ModerationLog) @@ -951,16 +908,17 @@ defmodule Pleroma.Web.AdminAPI.UserControllerTest do    defp user_response(user, attrs \\ %{}) do      %{ -      "deactivated" => user.deactivated, +      "is_active" => user.is_active,        "id" => user.id, +      "email" => user.email,        "nickname" => user.nickname,        "roles" => %{"admin" => false, "moderator" => false},        "local" => user.local,        "tags" => [],        "avatar" => User.avatar_url(user) |> MediaProxy.url(),        "display_name" => HTML.strip_tags(user.name || user.nickname), -      "confirmation_pending" => false, -      "approval_pending" => false, +      "is_confirmed" => true, +      "is_approved" => true,        "url" => user.ap_id,        "registration_reason" => nil,        "actor_type" => "Person" diff --git a/test/pleroma/web/admin_api/search_test.exs b/test/pleroma/web/admin_api/search_test.exs index 9bc58640c..b8eeec65b 100644 --- a/test/pleroma/web/admin_api/search_test.exs +++ b/test/pleroma/web/admin_api/search_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.SearchTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Web.AdminAPI.Search @@ -47,9 +47,9 @@ defmodule Pleroma.Web.AdminAPI.SearchTest do      end      test "it returns active/deactivated users" do -      insert(:user, deactivated: true) -      insert(:user, deactivated: true) -      insert(:user, deactivated: false) +      insert(:user, is_active: false) +      insert(:user, is_active: false) +      insert(:user, is_active: true)        {:ok, _results, active_count} =          Search.user(%{ @@ -70,7 +70,7 @@ defmodule Pleroma.Web.AdminAPI.SearchTest do      test "it returns specific user" do        insert(:user)        insert(:user) -      user = insert(:user, nickname: "bob", local: true, deactivated: false) +      user = insert(:user, nickname: "bob", local: true, is_active: true)        {:ok, _results, total_count} = Search.user(%{query: ""}) @@ -182,7 +182,7 @@ defmodule Pleroma.Web.AdminAPI.SearchTest do      end      test "it returns unapproved user" do -      unapproved = insert(:user, approval_pending: true) +      unapproved = insert(:user, is_approved: false)        insert(:user)        insert(:user) @@ -193,7 +193,7 @@ defmodule Pleroma.Web.AdminAPI.SearchTest do      end      test "it returns unconfirmed user" do -      unconfirmed = insert(:user, confirmation_pending: true) +      unconfirmed = insert(:user, is_confirmed: false)        insert(:user)        insert(:user) diff --git a/test/pleroma/web/admin_api/views/account_view_test.exs b/test/pleroma/web/admin_api/views/account_view_test.exs new file mode 100644 index 000000000..025726c73 --- /dev/null +++ b/test/pleroma/web/admin_api/views/account_view_test.exs @@ -0,0 +1,16 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.AdminAPI.AccountViewTest do +  use Pleroma.DataCase, async: true +  import Pleroma.Factory +  alias Pleroma.Web.AdminAPI.AccountView + +  describe "show.json" do +    test "renders the user's email" do +      user = insert(:user, email: "yolo@yolofam.tld") +      assert %{"email" => "yolo@yolofam.tld"} = AccountView.render("show.json", %{user: user}) +    end +  end +end diff --git a/test/pleroma/web/admin_api/views/moderation_log_view_test.exs b/test/pleroma/web/admin_api/views/moderation_log_view_test.exs index e6c5aaa7f..4efe4c4c8 100644 --- a/test/pleroma/web/admin_api/views/moderation_log_view_test.exs +++ b/test/pleroma/web/admin_api/views/moderation_log_view_test.exs @@ -1,14 +1,15 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.ModerationLogViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.AdminAPI.ModerationLogView    describe "renders `report_note_delete` log messages" do      setup do        log1 = %Pleroma.ModerationLog{ +        id: 1,          data: %{            "action" => "report_note_delete",            "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"}, @@ -21,6 +22,7 @@ defmodule Pleroma.Web.AdminAPI.ModerationLogViewTest do        }        log2 = %Pleroma.ModerationLog{ +        id: 2,          data: %{            "action" => "report_note_delete",            "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"}, @@ -42,6 +44,7 @@ defmodule Pleroma.Web.AdminAPI.ModerationLogViewTest do               ) == %{                 items: [                   %{ +                   id: 1,                     data: %{                       "action" => "report_note_delete",                       "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"}, @@ -59,6 +62,7 @@ defmodule Pleroma.Web.AdminAPI.ModerationLogViewTest do                     time: 1_605_622_400                   },                   %{ +                   id: 2,                     data: %{                       "action" => "report_note_delete",                       "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"}, @@ -82,6 +86,7 @@ defmodule Pleroma.Web.AdminAPI.ModerationLogViewTest do      test "renders `report_note_delete` log message", %{log1: log} do        assert ModerationLogView.render("show.json", %{log_entry: log}) == %{ +               id: 1,                 data: %{                   "action" => "report_note_delete",                   "actor" => %{"id" => "A1I7G8", "nickname" => "admin", "type" => "user"}, diff --git a/test/pleroma/web/admin_api/views/report_view_test.exs b/test/pleroma/web/admin_api/views/report_view_test.exs index 5a02292be..093e2d95d 100644 --- a/test/pleroma/web/admin_api/views/report_view_test.exs +++ b/test/pleroma/web/admin_api/views/report_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.AdminAPI.ReportViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory @@ -143,4 +143,29 @@ defmodule Pleroma.Web.AdminAPI.ReportViewTest do      assert %{} = ReportView.render("show.json", Report.extract_report_info(activity))    end + +  test "reports are ordered newest first" do +    user = insert(:user) +    other_user = insert(:user) + +    {:ok, report1} = +      CommonAPI.report(user, %{ +        account_id: other_user.id, +        comment: "first report" +      }) + +    {:ok, report2} = +      CommonAPI.report(user, %{ +        account_id: other_user.id, +        comment: "second report" +      }) + +    %{reports: rendered} = +      ReportView.render("index.json", +        reports: Pleroma.Web.ActivityPub.Utils.get_reports(%{}, 1, 50) +      ) + +    assert report2.id == rendered |> Enum.at(0) |> Map.get(:id) +    assert report1.id == rendered |> Enum.at(1) |> Map.get(:id) +  end  end diff --git a/test/pleroma/web/api_spec/schema_examples_test.exs b/test/pleroma/web/api_spec/schema_examples_test.exs index f00e834fc..981890d77 100644 --- a/test/pleroma/web/api_spec/schema_examples_test.exs +++ b/test/pleroma/web/api_spec/schema_examples_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ApiSpec.SchemaExamplesTest do diff --git a/test/pleroma/web/auth/auth_controller_test.exs b/test/pleroma/web/auth/auth_controller_test.exs index 498554060..a869389e3 100644 --- a/test/pleroma/web/auth/auth_controller_test.exs +++ b/test/pleroma/web/auth/auth_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Auth.AuthControllerTest do diff --git a/test/pleroma/web/auth/authenticator_test.exs b/test/pleroma/web/auth/authenticator_test.exs index d54253343..e1f30e835 100644 --- a/test/pleroma/web/auth/authenticator_test.exs +++ b/test/pleroma/web/auth/authenticator_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Auth.AuthenticatorTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Web.Auth.Authenticator    import Pleroma.Factory diff --git a/test/pleroma/web/auth/basic_auth_test.exs b/test/pleroma/web/auth/basic_auth_test.exs index bf6e3d2fc..2816aae4c 100644 --- a/test/pleroma/web/auth/basic_auth_test.exs +++ b/test/pleroma/web/auth/basic_auth_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Auth.BasicAuthTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory @@ -11,7 +11,7 @@ defmodule Pleroma.Web.Auth.BasicAuthTest do      conn: conn    } do      user = insert(:user) -    assert Pbkdf2.verify_pass("test", user.password_hash) +    assert Pleroma.Password.Pbkdf2.verify_pass("test", user.password_hash)      basic_auth_contents =        (URI.encode_www_form(user.nickname) <> ":" <> URI.encode_www_form("test")) diff --git a/test/pleroma/web/auth/pleroma_authenticator_test.exs b/test/pleroma/web/auth/pleroma_authenticator_test.exs index 1ba0dfecc..b1397c523 100644 --- a/test/pleroma/web/auth/pleroma_authenticator_test.exs +++ b/test/pleroma/web/auth/pleroma_authenticator_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Auth.PleromaAuthenticatorTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Web.Auth.PleromaAuthenticator    import Pleroma.Factory @@ -11,7 +11,13 @@ defmodule Pleroma.Web.Auth.PleromaAuthenticatorTest do    setup do      password = "testpassword"      name = "AgentSmith" -    user = insert(:user, nickname: name, password_hash: Pbkdf2.hash_pwd_salt(password)) + +    user = +      insert(:user, +        nickname: name, +        password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password) +      ) +      {:ok, [user: user, name: name, password: password]}    end diff --git a/test/pleroma/web/auth/totp_authenticator_test.exs b/test/pleroma/web/auth/totp_authenticator_test.exs index 84d4cd840..ac4209f2d 100644 --- a/test/pleroma/web/auth/totp_authenticator_test.exs +++ b/test/pleroma/web/auth/totp_authenticator_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Auth.TOTPAuthenticatorTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.MFA    alias Pleroma.MFA.BackupCodes @@ -34,7 +34,7 @@ defmodule Pleroma.Web.Auth.TOTPAuthenticatorTest do      hashed_codes =        backup_codes -      |> Enum.map(&Pbkdf2.hash_pwd_salt(&1)) +      |> Enum.map(&Pleroma.Password.Pbkdf2.hash_pwd_salt(&1))      user =        insert(:user, diff --git a/test/pleroma/web/chat_channel_test.exs b/test/pleroma/web/chat_channel_test.exs index 32170873d..29999701c 100644 --- a/test/pleroma/web/chat_channel_test.exs +++ b/test/pleroma/web/chat_channel_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ChatChannelTest do @@ -33,7 +33,7 @@ defmodule Pleroma.Web.ChatChannelTest do      end      test "it ignores messages above a certain length", %{socket: socket} do -      Pleroma.Config.put([:instance, :chat_limit], 2) +      clear_config([:instance, :chat_limit], 2)        push(socket, "new_msg", %{"text" => "123"})        refute_broadcast("new_msg", %{text: "123"})      end diff --git a/test/pleroma/web/common_api/utils_test.exs b/test/pleroma/web/common_api/utils_test.exs index 8c79a9a83..b0e567ff0 100644 --- a/test/pleroma/web/common_api/utils_test.exs +++ b/test/pleroma/web/common_api/utils_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.CommonAPI.UtilsTest do diff --git a/test/pleroma/web/common_api_test.exs b/test/pleroma/web/common_api_test.exs index c1b1af073..be94c93c2 100644 --- a/test/pleroma/web/common_api_test.exs +++ b/test/pleroma/web/common_api_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.CommonAPITest do @@ -25,6 +25,11 @@ defmodule Pleroma.Web.CommonAPITest do    require Pleroma.Constants +  setup_all do +    Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) +    :ok +  end +    setup do: clear_config([:instance, :safe_dm_mentions])    setup do: clear_config([:instance, :limit])    setup do: clear_config([:instance, :max_pinned_statuses]) @@ -39,7 +44,7 @@ defmodule Pleroma.Web.CommonAPITest do            poll: %{expires_in: 600, options: ["reimu", "marisa"]}          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert object.data["type"] == "Question"        assert object.data["oneOf"] |> length() == 2 @@ -174,7 +179,7 @@ defmodule Pleroma.Web.CommonAPITest do        assert other_user.ap_id not in activity.recipients -      object = Object.normalize(activity, false) +      object = Object.normalize(activity, fetch: false)        assert object.data["content"] == "uguu<br/>uguuu"      end @@ -194,7 +199,7 @@ defmodule Pleroma.Web.CommonAPITest do        assert other_user.ap_id not in activity.recipients -      object = Object.normalize(activity, false) +      object = Object.normalize(activity, fetch: false)        assert object.data["content"] ==                 "<a href=\"https://example.org\" rel=\"ugc\">https://example.org</a> is the site of <span class=\"h-card\"><a class=\"u-url mention\" data-user=\"#{ @@ -215,7 +220,7 @@ defmodule Pleroma.Web.CommonAPITest do        assert activity.data["type"] == "Create"        assert activity.local -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert object.data["type"] == "ChatMessage"        assert object.data["to"] == [recipient.ap_id] @@ -234,7 +239,7 @@ defmodule Pleroma.Web.CommonAPITest do      end      test "it reject messages over the local limit" do -      Pleroma.Config.put([:instance, :chat_limit], 2) +      clear_config([:instance, :chat_limit], 2)        author = insert(:user)        recipient = insert(:user) @@ -281,7 +286,7 @@ defmodule Pleroma.Web.CommonAPITest do        clear_config([:instance, :federating], true) -      Object.normalize(post, false) +      Object.normalize(post, fetch: false)        |> Object.prune()        with_mock Pleroma.Web.Federator, @@ -475,7 +480,7 @@ defmodule Pleroma.Web.CommonAPITest do      jafnhar = insert(:user)      tridi = insert(:user) -    Pleroma.Config.put([:instance, :safe_dm_mentions], true) +    clear_config([:instance, :safe_dm_mentions], true)      {:ok, activity} =        CommonAPI.post(har, %{ @@ -491,21 +496,55 @@ defmodule Pleroma.Web.CommonAPITest do      user = insert(:user)      {:ok, activity} = CommonAPI.post(user, %{status: "#2hu #2HU"}) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false) -    assert object.data["tag"] == ["2hu"] +    assert Object.tags(object) == ["2hu"]    end    test "it adds emoji in the object" do      user = insert(:user)      {:ok, activity} = CommonAPI.post(user, %{status: ":firefox:"}) -    assert Object.normalize(activity).data["emoji"]["firefox"] +    assert Object.normalize(activity, fetch: false).data["emoji"]["firefox"]    end    describe "posting" do +    test "it adds an emoji on an external site" do +      user = insert(:user) +      {:ok, activity} = CommonAPI.post(user, %{status: "hey :external_emoji:"}) + +      assert %{"external_emoji" => url} = Object.normalize(activity).data["emoji"] +      assert url == "https://example.com/emoji.png" + +      {:ok, activity} = CommonAPI.post(user, %{status: "hey :blank:"}) + +      assert %{"blank" => url} = Object.normalize(activity).data["emoji"] +      assert url == "#{Pleroma.Web.base_url()}/emoji/blank.png" +    end + +    test "it copies emoji from the subject of the parent post" do +      %Object{} = +        object = +        Object.normalize("https://patch.cx/objects/a399c28e-c821-4820-bc3e-4afeb044c16f", +          fetch: true +        ) + +      activity = Activity.get_create_by_object_ap_id(object.data["id"]) +      user = insert(:user) + +      {:ok, reply_activity} = +        CommonAPI.post(user, %{ +          in_reply_to_id: activity.id, +          status: ":joker_disapprove:", +          spoiler_text: ":joker_smile:" +        }) + +      assert Object.normalize(reply_activity).data["emoji"][":joker_smile:"] +      refute Object.normalize(reply_activity).data["emoji"][":joker_disapprove:"] +    end +      test "deactivated users can't post" do -      user = insert(:user, deactivated: true) +      user = insert(:user, is_active: false)        assert {:error, _} = CommonAPI.post(user, %{status: "ye"})      end @@ -539,7 +578,7 @@ defmodule Pleroma.Web.CommonAPITest do            content_type: "text/html"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert object.data["content"] == "<p><b>2hu</b></p>alert('xss')"        assert object.data["source"] == post @@ -556,7 +595,7 @@ defmodule Pleroma.Web.CommonAPITest do            content_type: "text/markdown"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert object.data["content"] == "<p><b>2hu</b></p>"        assert object.data["source"] == post @@ -629,7 +668,7 @@ defmodule Pleroma.Web.CommonAPITest do      end      test "it validates character limits are correctly enforced" do -      Pleroma.Config.put([:instance, :limit], 5) +      clear_config([:instance, :limit], 5)        user = insert(:user) @@ -731,6 +770,22 @@ defmodule Pleroma.Web.CommonAPITest do        refute Visibility.visible_for_user?(announce_activity, nil)      end +    test "author can repeat own private statuses" do +      author = insert(:user) +      follower = insert(:user) +      CommonAPI.follow(follower, author) + +      {:ok, activity} = CommonAPI.post(author, %{status: "cofe", visibility: "private"}) + +      {:ok, %Activity{} = announce_activity} = CommonAPI.repeat(activity.id, author) + +      assert Visibility.is_private?(announce_activity) +      refute Visibility.visible_for_user?(announce_activity, nil) + +      assert Visibility.visible_for_user?(activity, follower) +      assert {:error, :not_found} = CommonAPI.repeat(activity.id, follower) +    end +      test "favoriting a status" do        user = insert(:user)        other_user = insert(:user) @@ -764,7 +819,7 @@ defmodule Pleroma.Web.CommonAPITest do    describe "pinned statuses" do      setup do -      Pleroma.Config.put([:instance, :max_pinned_statuses], 1) +      clear_config([:instance, :max_pinned_statuses], 1)        user = insert(:user)        {:ok, activity} = CommonAPI.post(user, %{status: "HI!!!"}) @@ -772,13 +827,17 @@ defmodule Pleroma.Web.CommonAPITest do        [user: user, activity: activity]      end +    test "activity not found error", %{user: user} do +      assert {:error, :not_found} = CommonAPI.pin("id", user) +    end +      test "pin status", %{user: user, activity: activity} do        assert {:ok, ^activity} = CommonAPI.pin(activity.id, user) -      id = activity.id +      %{data: %{"id" => object_id}} = Object.normalize(activity)        user = refresh_record(user) -      assert %User{pinned_activities: [^id]} = user +      assert user.pinned_objects |> Map.keys() == [object_id]      end      test "pin poll", %{user: user} do @@ -790,10 +849,11 @@ defmodule Pleroma.Web.CommonAPITest do        assert {:ok, ^activity} = CommonAPI.pin(activity.id, user) -      id = activity.id +      %{data: %{"id" => object_id}} = Object.normalize(activity) +        user = refresh_record(user) -      assert %User{pinned_activities: [^id]} = user +      assert user.pinned_objects |> Map.keys() == [object_id]      end      test "unlisted statuses can be pinned", %{user: user} do @@ -804,7 +864,7 @@ defmodule Pleroma.Web.CommonAPITest do      test "only self-authored can be pinned", %{activity: activity} do        user = insert(:user) -      assert {:error, "Could not pin"} = CommonAPI.pin(activity.id, user) +      assert {:error, :ownership_error} = CommonAPI.pin(activity.id, user)      end      test "max pinned statuses", %{user: user, activity: activity_one} do @@ -814,8 +874,12 @@ defmodule Pleroma.Web.CommonAPITest do        user = refresh_record(user) -      assert {:error, "You have already pinned the maximum number of statuses"} = -               CommonAPI.pin(activity_two.id, user) +      assert {:error, :pinned_statuses_limit_reached} = CommonAPI.pin(activity_two.id, user) +    end + +    test "only public can be pinned", %{user: user} do +      {:ok, activity} = CommonAPI.post(user, %{status: "private status", visibility: "private"}) +      {:error, :visibility_error} = CommonAPI.pin(activity.id, user)      end      test "unpin status", %{user: user, activity: activity} do @@ -829,7 +893,7 @@ defmodule Pleroma.Web.CommonAPITest do        user = refresh_record(user) -      assert %User{pinned_activities: []} = user +      assert user.pinned_objects == %{}      end      test "should unpin when deleting a status", %{user: user, activity: activity} do @@ -841,7 +905,40 @@ defmodule Pleroma.Web.CommonAPITest do        user = refresh_record(user) -      assert %User{pinned_activities: []} = user +      assert user.pinned_objects == %{} +    end + +    test "ephemeral activity won't be deleted if was pinned", %{user: user} do +      {:ok, activity} = CommonAPI.post(user, %{status: "Hello!", expires_in: 601}) + +      assert Pleroma.Workers.PurgeExpiredActivity.get_expiration(activity.id) + +      {:ok, _activity} = CommonAPI.pin(activity.id, user) +      refute Pleroma.Workers.PurgeExpiredActivity.get_expiration(activity.id) + +      user = refresh_record(user) +      {:ok, _} = CommonAPI.unpin(activity.id, user) + +      # recreates expiration job on unpin +      assert Pleroma.Workers.PurgeExpiredActivity.get_expiration(activity.id) +    end + +    test "ephemeral activity deletion job won't be deleted on pinning error", %{ +      user: user, +      activity: activity +    } do +      clear_config([:instance, :max_pinned_statuses], 1) + +      {:ok, _activity} = CommonAPI.pin(activity.id, user) + +      {:ok, activity2} = CommonAPI.post(user, %{status: "another status", expires_in: 601}) + +      assert Pleroma.Workers.PurgeExpiredActivity.get_expiration(activity2.id) + +      user = refresh_record(user) +      {:error, :pinned_statuses_limit_reached} = CommonAPI.pin(activity2.id, user) + +      assert Pleroma.Workers.PurgeExpiredActivity.get_expiration(activity2.id)      end    end @@ -1211,7 +1308,7 @@ defmodule Pleroma.Web.CommonAPITest do            poll: %{options: ["Yes", "No"], expires_in: 20}          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        {:ok, _, object} = CommonAPI.vote(other_user, object, [0]) @@ -1231,7 +1328,7 @@ defmodule Pleroma.Web.CommonAPITest do            length: 180_000          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert object.data["title"] == "lain radio episode 1" @@ -1250,7 +1347,7 @@ defmodule Pleroma.Web.CommonAPITest do            visibility: "private"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert object.data["title"] == "lain radio episode 1" diff --git a/test/pleroma/web/endpoint/metrics_exporter_test.exs b/test/pleroma/web/endpoint/metrics_exporter_test.exs index 875addc96..376e82149 100644 --- a/test/pleroma/web/endpoint/metrics_exporter_test.exs +++ b/test/pleroma/web/endpoint/metrics_exporter_test.exs @@ -1,8 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Endpoint.MetricsExporterTest do +  # Modifies AppEnv, has to stay synchronous    use Pleroma.Web.ConnCase    alias Pleroma.Web.Endpoint.MetricsExporter diff --git a/test/pleroma/web/fallback_test.exs b/test/pleroma/web/fallback_test.exs index 46c7bad1c..512baf813 100644 --- a/test/pleroma/web/fallback_test.exs +++ b/test/pleroma/web/fallback_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.FallbackTest do diff --git a/test/pleroma/web/federator_test.exs b/test/pleroma/web/federator_test.exs index 67001add7..532ee6d30 100644 --- a/test/pleroma/web/federator_test.exs +++ b/test/pleroma/web/federator_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.FederatorTest do @@ -56,7 +56,7 @@ defmodule Pleroma.Web.FederatorTest do        activity: activity,        relay_mock: relay_mock      } do -      Pleroma.Config.put([:instance, :allow_relay], false) +      clear_config([:instance, :allow_relay], false)        with_mocks([relay_mock]) do          Federator.publish(activity) @@ -155,9 +155,9 @@ defmodule Pleroma.Web.FederatorTest do      end      test "it does not crash if MRF rejects the post" do -      Pleroma.Config.put([:mrf_keyword, :reject], ["lain"]) +      clear_config([:mrf_keyword, :reject], ["lain"]) -      Pleroma.Config.put( +      clear_config(          [:mrf, :policies],          Pleroma.Web.ActivityPub.MRF.KeywordPolicy        ) diff --git a/test/pleroma/web/feed/tag_controller_test.exs b/test/pleroma/web/feed/tag_controller_test.exs index e4084b0e5..5c9201de1 100644 --- a/test/pleroma/web/feed/tag_controller_test.exs +++ b/test/pleroma/web/feed/tag_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Feed.TagControllerTest do @@ -8,7 +8,6 @@ defmodule Pleroma.Web.Feed.TagControllerTest do    import Pleroma.Factory    import SweetXml -  alias Pleroma.Config    alias Pleroma.Object    alias Pleroma.Web.CommonAPI    alias Pleroma.Web.Feed.FeedView @@ -16,7 +15,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do    setup do: clear_config([:feed])    test "gets a feed (ATOM)", %{conn: conn} do -    Config.put( +    clear_config(        [:feed, :post_title],        %{max_length: 25, omission: "..."}      ) @@ -24,7 +23,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      user = insert(:user)      {:ok, activity1} = CommonAPI.post(user, %{status: "yeah #PleromaArt"}) -    object = Object.normalize(activity1) +    object = Object.normalize(activity1, fetch: false)      object_data =        Map.put(object.data, "attachment", [ @@ -83,7 +82,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do    end    test "gets a feed (RSS)", %{conn: conn} do -    Config.put( +    clear_config(        [:feed, :post_title],        %{max_length: 25, omission: "..."}      ) @@ -91,7 +90,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do      user = insert(:user)      {:ok, activity1} = CommonAPI.post(user, %{status: "yeah #PleromaArt"}) -    object = Object.normalize(activity1) +    object = Object.normalize(activity1, fetch: false)      object_data =        Map.put(object.data, "attachment", [ @@ -131,7 +130,7 @@ defmodule Pleroma.Web.Feed.TagControllerTest do               '#{Pleroma.Web.base_url()}/tags/pleromaart.rss'      assert xpath(xml, ~x"//channel/webfeeds:logo/text()") == -             '#{Pleroma.Web.base_url()}/static/logo.png' +             '#{Pleroma.Web.base_url()}/static/logo.svg'      assert xpath(xml, ~x"//channel/item/title/text()"l) == [               '42 This is :moominmamm...', @@ -147,8 +146,8 @@ defmodule Pleroma.Web.Feed.TagControllerTest do               "https://peertube.moe/static/webseed/df5f464b-be8d-46fb-ad81-2d4c2d1630e3-480.mp4"             ] -    obj1 = Object.normalize(activity1) -    obj2 = Object.normalize(activity2) +    obj1 = Object.normalize(activity1, fetch: false) +    obj2 = Object.normalize(activity2, fetch: false)      assert xpath(xml, ~x"//channel/item/description/text()"sl) == [               HtmlEntities.decode(FeedView.activity_content(obj2.data)), diff --git a/test/pleroma/web/feed/user_controller_test.exs b/test/pleroma/web/feed/user_controller_test.exs index 16f002717..408653d92 100644 --- a/test/pleroma/web/feed/user_controller_test.exs +++ b/test/pleroma/web/feed/user_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Feed.UserControllerTest do @@ -8,7 +8,6 @@ defmodule Pleroma.Web.Feed.UserControllerTest do    import Pleroma.Factory    import SweetXml -  alias Pleroma.Config    alias Pleroma.Object    alias Pleroma.User    alias Pleroma.Web.CommonAPI @@ -20,7 +19,7 @@ defmodule Pleroma.Web.Feed.UserControllerTest do      setup do: clear_config([:feed])      setup do -      Config.put( +      clear_config(          [:feed, :post_title],          %{max_length: 15, omission: "..."}        ) @@ -58,7 +57,7 @@ defmodule Pleroma.Web.Feed.UserControllerTest do          )        note_activity2 = insert(:note_activity, note: note2) -      object = Object.normalize(note_activity) +      object = Object.normalize(note_activity, fetch: false)        [user: user, object: object, max_id: note_activity2.id]      end @@ -236,7 +235,7 @@ defmodule Pleroma.Web.Feed.UserControllerTest do      setup do: clear_config([:instance, :public])      test "returns 404 for user feed", %{conn: conn} do -      Config.put([:instance, :public], false) +      clear_config([:instance, :public], false)        user = insert(:user)        {:ok, _} = CommonAPI.post(user, %{status: "test"}) diff --git a/test/pleroma/web/mastodon_api/controllers/account_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/account_controller_test.exs index 3361c8669..a327c0d1d 100644 --- a/test/pleroma/web/mastodon_api/controllers/account_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/account_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do @@ -29,6 +29,45 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do                 |> json_response_and_validate_schema(404)      end +    test "relationship field" do +      %{conn: conn, user: user} = oauth_access(["read"]) + +      other_user = insert(:user) + +      response = +        conn +        |> get("/api/v1/accounts/#{other_user.id}") +        |> json_response_and_validate_schema(200) + +      assert response["id"] == other_user.id +      assert response["pleroma"]["relationship"] == %{} + +      assert %{"pleroma" => %{"relationship" => %{"following" => false, "followed_by" => false}}} = +               conn +               |> get("/api/v1/accounts/#{other_user.id}?with_relationships=true") +               |> json_response_and_validate_schema(200) + +      {:ok, _, %{id: other_id}} = User.follow(user, other_user) + +      assert %{ +               "id" => ^other_id, +               "pleroma" => %{"relationship" => %{"following" => true, "followed_by" => false}} +             } = +               conn +               |> get("/api/v1/accounts/#{other_id}?with_relationships=true") +               |> json_response_and_validate_schema(200) + +      {:ok, _, _} = User.follow(other_user, user) + +      assert %{ +               "id" => ^other_id, +               "pleroma" => %{"relationship" => %{"following" => true, "followed_by" => true}} +             } = +               conn +               |> get("/api/v1/accounts/#{other_id}?with_relationships=true") +               |> json_response_and_validate_schema(200) +    end +      test "works by nickname" do        user = insert(:user) @@ -126,7 +165,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      end      test "returns 404 for deactivated user", %{conn: conn} do -      user = insert(:user, deactivated: true) +      user = insert(:user, is_active: false)        assert %{"error" => "Can't find user"} =                 conn @@ -256,7 +295,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      end      test "deactivated user", %{conn: conn} do -      user = insert(:user, deactivated: true) +      user = insert(:user, is_active: false)        assert %{"error" => "Can't find user"} ==                 conn @@ -469,6 +508,21 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do                 }               ] = result      end + +    test "paginates a user's statuses", %{user: user, conn: conn} do +      {:ok, post_1} = CommonAPI.post(user, %{status: "first post"}) +      {:ok, post_2} = CommonAPI.post(user, %{status: "second post"}) + +      response_1 = get(conn, "/api/v1/accounts/#{user.id}/statuses?limit=1") +      assert [res] = json_response(response_1, 200) +      assert res["id"] == post_2.id + +      response_2 = get(conn, "/api/v1/accounts/#{user.id}/statuses?limit=1&max_id=#{res["id"]}") +      assert [res] = json_response(response_2, 200) +      assert res["id"] == post_1.id + +      refute response_1 == response_2 +    end    end    defp local_and_remote_activities(%{local: local, remote: remote}) do @@ -575,6 +629,45 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        assert [%{"id" => ^user_id}] = json_response_and_validate_schema(conn, 200)      end +    test "following with relationship", %{conn: conn, user: user} do +      other_user = insert(:user) +      {:ok, %{id: id}, _} = User.follow(other_user, user) + +      assert [ +               %{ +                 "id" => ^id, +                 "pleroma" => %{ +                   "relationship" => %{ +                     "id" => ^id, +                     "following" => false, +                     "followed_by" => true +                   } +                 } +               } +             ] = +               conn +               |> get("/api/v1/accounts/#{user.id}/followers?with_relationships=true") +               |> json_response_and_validate_schema(200) + +      {:ok, _, _} = User.follow(user, other_user) + +      assert [ +               %{ +                 "id" => ^id, +                 "pleroma" => %{ +                   "relationship" => %{ +                     "id" => ^id, +                     "following" => true, +                     "followed_by" => true +                   } +                 } +               } +             ] = +               conn +               |> get("/api/v1/accounts/#{user.id}/followers?with_relationships=true") +               |> json_response_and_validate_schema(200) +    end +      test "getting followers, hide_followers", %{user: user, conn: conn} do        other_user = insert(:user, hide_followers: true)        {:ok, _user, _other_user} = User.follow(user, other_user) @@ -645,6 +738,24 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        assert id == to_string(other_user.id)      end +    test "following with relationship", %{conn: conn, user: user} do +      other_user = insert(:user) +      {:ok, user, other_user} = User.follow(user, other_user) + +      conn = get(conn, "/api/v1/accounts/#{user.id}/following?with_relationships=true") + +      id = other_user.id + +      assert [ +               %{ +                 "id" => ^id, +                 "pleroma" => %{ +                   "relationship" => %{"id" => ^id, "following" => true, "followed_by" => false} +                 } +               } +             ] = json_response_and_validate_schema(conn, 200) +    end +      test "getting following, hide_follows, other user requesting" do        user = insert(:user, hide_follows: true)        other_user = insert(:user) @@ -992,7 +1103,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        assert %{"error" => "{\"email\":[\"Invalid email\"]}"} =                 json_response_and_validate_schema(conn, 400) -      Pleroma.Config.put([User, :email_blacklist], []) +      clear_config([User, :email_blacklist], [])        conn =          build_conn() @@ -1012,8 +1123,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        user = Repo.preload(token_from_db, :user).user        assert user -      refute user.confirmation_pending -      refute user.approval_pending +      assert user.is_confirmed +      assert user.is_approved      end      test "registers but does not log in with :account_activation_required", %{conn: conn} do @@ -1073,7 +1184,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        refute response["token_type"]        user = Repo.get_by(User, email: "lain@example.org") -      assert user.confirmation_pending +      refute user.is_confirmed      end      test "registers but does not log in with :account_approval_required", %{conn: conn} do @@ -1135,7 +1246,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do        user = Repo.get_by(User, email: "lain@example.org") -      assert user.approval_pending +      refute user.is_approved        assert user.registration_reason == "I'm a cool dude, bro"      end @@ -1411,8 +1522,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do                 |> json_response_and_validate_schema(:ok)        assert Token |> Repo.get_by(token: access_token) |> Repo.preload(:user) |> Map.get(:user) - -      Cachex.del(:used_captcha_cache, token)      end      test "returns 400 if any captcha field is not provided", %{conn: conn} do @@ -1552,7 +1661,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      result =        conn -      |> assign(:user, user)        |> get("/api/v1/mutes")        |> json_response_and_validate_schema(200) @@ -1560,7 +1668,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      result =        conn -      |> assign(:user, user)        |> get("/api/v1/mutes?limit=1")        |> json_response_and_validate_schema(200) @@ -1568,7 +1675,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      result =        conn -      |> assign(:user, user)        |> get("/api/v1/mutes?since_id=#{id1}")        |> json_response_and_validate_schema(200) @@ -1576,7 +1682,6 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      result =        conn -      |> assign(:user, user)        |> get("/api/v1/mutes?since_id=#{id1}&max_id=#{id3}")        |> json_response_and_validate_schema(200) @@ -1584,13 +1689,45 @@ defmodule Pleroma.Web.MastodonAPI.AccountControllerTest do      result =        conn -      |> assign(:user, user)        |> get("/api/v1/mutes?since_id=#{id1}&limit=1")        |> json_response_and_validate_schema(200)      assert [%{"id" => ^id2}] = result    end +  test "list of mutes with with_relationships parameter" do +    %{user: user, conn: conn} = oauth_access(["read:mutes"]) +    %{id: id1} = other_user1 = insert(:user) +    %{id: id2} = other_user2 = insert(:user) +    %{id: id3} = other_user3 = insert(:user) + +    {:ok, _, _} = User.follow(other_user1, user) +    {:ok, _, _} = User.follow(other_user2, user) +    {:ok, _, _} = User.follow(other_user3, user) + +    {:ok, _} = User.mute(user, other_user1) +    {:ok, _} = User.mute(user, other_user2) +    {:ok, _} = User.mute(user, other_user3) + +    assert [ +             %{ +               "id" => ^id1, +               "pleroma" => %{"relationship" => %{"muting" => true, "followed_by" => true}} +             }, +             %{ +               "id" => ^id2, +               "pleroma" => %{"relationship" => %{"muting" => true, "followed_by" => true}} +             }, +             %{ +               "id" => ^id3, +               "pleroma" => %{"relationship" => %{"muting" => true, "followed_by" => true}} +             } +           ] = +             conn +             |> get("/api/v1/mutes?with_relationships=true") +             |> json_response_and_validate_schema(200) +  end +    test "getting a list of blocks" do      %{user: user, conn: conn} = oauth_access(["read:blocks"])      %{id: id1} = other_user1 = insert(:user) diff --git a/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs index a0b8b126c..76d81b942 100644 --- a/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/app_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.AppControllerTest do @@ -12,22 +12,26 @@ defmodule Pleroma.Web.MastodonAPI.AppControllerTest do    import Pleroma.Factory    test "apps/verify_credentials", %{conn: conn} do -    token = insert(:oauth_token) +    user_bound_token = insert(:oauth_token) +    app_bound_token = insert(:oauth_token, user: nil) +    refute app_bound_token.user -    conn = -      conn -      |> put_req_header("authorization", "Bearer #{token.token}") -      |> get("/api/v1/apps/verify_credentials") +    for token <- [app_bound_token, user_bound_token] do +      conn = +        conn +        |> put_req_header("authorization", "Bearer #{token.token}") +        |> get("/api/v1/apps/verify_credentials") -    app = Repo.preload(token, :app).app +      app = Repo.preload(token, :app).app -    expected = %{ -      "name" => app.client_name, -      "website" => app.website, -      "vapid_key" => Push.vapid_config() |> Keyword.get(:public_key) -    } +      expected = %{ +        "name" => app.client_name, +        "website" => app.website, +        "vapid_key" => Push.vapid_config() |> Keyword.get(:public_key) +      } -    assert expected == json_response_and_validate_schema(conn, 200) +      assert expected == json_response_and_validate_schema(conn, 200) +    end    end    test "creates an oauth app", %{conn: conn} do diff --git a/test/pleroma/web/mastodon_api/controllers/auth_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/auth_controller_test.exs index d7834c876..1872dfd59 100644 --- a/test/pleroma/web/mastodon_api/controllers/auth_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/auth_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.AuthControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Config    alias Pleroma.Repo @@ -136,7 +136,7 @@ defmodule Pleroma.Web.MastodonAPI.AuthControllerTest do      end      test "it returns 204 when user is deactivated", %{conn: conn, user: user} do -      {:ok, user} = Repo.update(Ecto.Changeset.change(user, deactivated: true, local: true)) +      {:ok, user} = Repo.update(Ecto.Changeset.change(user, is_active: false, local: true))        conn = post(conn, "/auth/password?email=#{user.email}")        assert empty_json_response(conn) diff --git a/test/pleroma/web/mastodon_api/controllers/conversation_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/conversation_controller_test.exs index b00615ac9..3176f1296 100644 --- a/test/pleroma/web/mastodon_api/controllers/conversation_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/conversation_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Conversation.Participation    alias Pleroma.User @@ -217,6 +217,32 @@ defmodule Pleroma.Web.MastodonAPI.ConversationControllerTest do      assert %{"ancestors" => [], "descendants" => []} == json_response(res_conn, 200)    end +  test "Removes a conversation", %{user: user_one, conn: conn} do +    user_two = insert(:user) +    token = insert(:oauth_token, user: user_one, scopes: ["read:statuses", "write:conversations"]) + +    {:ok, _direct} = create_direct_message(user_one, [user_two]) +    {:ok, _direct} = create_direct_message(user_one, [user_two]) + +    assert [%{"id" => conv1_id}, %{"id" => conv2_id}] = +             conn +             |> assign(:token, token) +             |> get("/api/v1/conversations") +             |> json_response_and_validate_schema(200) + +    assert %{} = +             conn +             |> assign(:token, token) +             |> delete("/api/v1/conversations/#{conv1_id}") +             |> json_response_and_validate_schema(200) + +    assert [%{"id" => ^conv2_id}] = +             conn +             |> assign(:token, token) +             |> get("/api/v1/conversations") +             |> json_response_and_validate_schema(200) +  end +    defp create_direct_message(sender, recips) do      hellos =        recips diff --git a/test/pleroma/web/mastodon_api/controllers/custom_emoji_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/custom_emoji_controller_test.exs index ab0027f90..cbb1d54a6 100644 --- a/test/pleroma/web/mastodon_api/controllers/custom_emoji_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/custom_emoji_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.CustomEmojiControllerTest do diff --git a/test/pleroma/web/mastodon_api/controllers/domain_block_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/domain_block_controller_test.exs index 664654500..0c3a7c0cf 100644 --- a/test/pleroma/web/mastodon_api/controllers/domain_block_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/domain_block_controller_test.exs @@ -1,8 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.DomainBlockControllerTest do +  # TODO: Should not need Cachex    use Pleroma.Web.ConnCase    alias Pleroma.User diff --git a/test/pleroma/web/mastodon_api/controllers/filter_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/filter_controller_test.exs index 0d426ec34..98ab9e717 100644 --- a/test/pleroma/web/mastodon_api/controllers/filter_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/filter_controller_test.exs @@ -1,152 +1,415 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.FilterControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true +  use Oban.Testing, repo: Pleroma.Repo -  alias Pleroma.Web.MastodonAPI.FilterView +  import Pleroma.Factory -  test "creating a filter" do -    %{conn: conn} = oauth_access(["write:filters"]) +  alias Pleroma.Filter +  alias Pleroma.Repo +  alias Pleroma.Workers.PurgeExpiredFilter -    filter = %Pleroma.Filter{ -      phrase: "knights", -      context: ["home"] -    } - -    conn = +  test "non authenticated creation request", %{conn: conn} do +    response =        conn        |> put_req_header("content-type", "application/json") -      |> post("/api/v1/filters", %{"phrase" => filter.phrase, context: filter.context}) - -    assert response = json_response_and_validate_schema(conn, 200) -    assert response["phrase"] == filter.phrase -    assert response["context"] == filter.context -    assert response["irreversible"] == false -    assert response["id"] != nil -    assert response["id"] != "" +      |> post("/api/v1/filters", %{"phrase" => "knights", context: ["home"]}) +      |> json_response(403) + +    assert response["error"] == "Invalid credentials." +  end + +  describe "creating" do +    setup do: oauth_access(["write:filters"]) + +    test "a common filter", %{conn: conn, user: user} do +      params = %{ +        phrase: "knights", +        context: ["home"], +        irreversible: true +      } + +      response = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/filters", params) +        |> json_response_and_validate_schema(200) + +      assert response["phrase"] == params.phrase +      assert response["context"] == params.context +      assert response["irreversible"] == true +      assert response["id"] != nil +      assert response["id"] != "" +      assert response["expires_at"] == nil + +      filter = Filter.get(response["id"], user) +      assert filter.hide == true +    end + +    test "a filter with expires_in", %{conn: conn, user: user} do +      in_seconds = 600 + +      response = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/filters", %{ +          "phrase" => "knights", +          context: ["home"], +          expires_in: in_seconds +        }) +        |> json_response_and_validate_schema(200) + +      assert response["irreversible"] == false + +      expires_at = +        NaiveDateTime.utc_now() +        |> NaiveDateTime.add(in_seconds) +        |> Pleroma.Web.CommonAPI.Utils.to_masto_date() + +      assert response["expires_at"] == expires_at + +      filter = Filter.get(response["id"], user) + +      id = filter.id + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: filter.id} +      ) + +      assert {:ok, %{id: ^id}} = +               perform_job(PurgeExpiredFilter, %{ +                 filter_id: filter.id +               }) + +      assert Repo.aggregate(Filter, :count, :id) == 0 +    end    end    test "fetching a list of filters" do      %{user: user, conn: conn} = oauth_access(["read:filters"]) -    query_one = %Pleroma.Filter{ -      user_id: user.id, -      filter_id: 1, -      phrase: "knights", -      context: ["home"] -    } +    %{filter_id: id1} = insert(:filter, user: user) +    %{filter_id: id2} = insert(:filter, user: user) -    query_two = %Pleroma.Filter{ -      user_id: user.id, -      filter_id: 2, -      phrase: "who", -      context: ["home"] -    } +    id1 = to_string(id1) +    id2 = to_string(id2) -    {:ok, filter_one} = Pleroma.Filter.create(query_one) -    {:ok, filter_two} = Pleroma.Filter.create(query_two) +    assert [%{"id" => ^id2}, %{"id" => ^id1}] = +             conn +             |> get("/api/v1/filters") +             |> json_response_and_validate_schema(200) +  end + +  test "fetching a list of filters without token", %{conn: conn} do +    insert(:filter)      response =        conn        |> get("/api/v1/filters") -      |> json_response_and_validate_schema(200) - -    assert response == -             render_json( -               FilterView, -               "index.json", -               filters: [filter_two, filter_one] -             ) +      |> json_response(403) + +    assert response["error"] == "Invalid credentials."    end    test "get a filter" do      %{user: user, conn: conn} = oauth_access(["read:filters"])      # check whole_word false -    query = %Pleroma.Filter{ -      user_id: user.id, -      filter_id: 2, -      phrase: "knight", -      context: ["home"], -      whole_word: false -    } - -    {:ok, filter} = Pleroma.Filter.create(query) +    filter = insert(:filter, user: user, whole_word: false) -    conn = get(conn, "/api/v1/filters/#{filter.filter_id}") +    resp1 = +      conn |> get("/api/v1/filters/#{filter.filter_id}") |> json_response_and_validate_schema(200) -    assert response = json_response_and_validate_schema(conn, 200) -    assert response["whole_word"] == false +    assert resp1["whole_word"] == false      # check whole_word true -    %{user: user, conn: conn} = oauth_access(["read:filters"]) - -    query = %Pleroma.Filter{ -      user_id: user.id, -      filter_id: 3, -      phrase: "knight", -      context: ["home"], -      whole_word: true -    } +    filter = insert(:filter, user: user, whole_word: true) -    {:ok, filter} = Pleroma.Filter.create(query) +    resp2 = +      conn |> get("/api/v1/filters/#{filter.filter_id}") |> json_response_and_validate_schema(200) -    conn = get(conn, "/api/v1/filters/#{filter.filter_id}") - -    assert response = json_response_and_validate_schema(conn, 200) -    assert response["whole_word"] == true +    assert resp2["whole_word"] == true    end -  test "update a filter" do -    %{user: user, conn: conn} = oauth_access(["write:filters"]) +  test "get a filter not_found error" do +    filter = insert(:filter) +    %{conn: conn} = oauth_access(["read:filters"]) -    query = %Pleroma.Filter{ -      user_id: user.id, -      filter_id: 2, -      phrase: "knight", -      context: ["home"], -      hide: true, -      whole_word: true -    } +    response = +      conn |> get("/api/v1/filters/#{filter.filter_id}") |> json_response_and_validate_schema(404) -    {:ok, _filter} = Pleroma.Filter.create(query) +    assert response["error"] == "Record not found" +  end + +  describe "updating a filter" do +    setup do: oauth_access(["write:filters"]) + +    test "common" do +      %{conn: conn, user: user} = oauth_access(["write:filters"]) + +      filter = +        insert(:filter, +          user: user, +          hide: true, +          whole_word: true +        ) + +      params = %{ +        phrase: "nii", +        context: ["public"], +        irreversible: false +      } + +      response = +        conn +        |> put_req_header("content-type", "application/json") +        |> put("/api/v1/filters/#{filter.filter_id}", params) +        |> json_response_and_validate_schema(200) + +      assert response["phrase"] == params.phrase +      assert response["context"] == params.context +      assert response["irreversible"] == false +      assert response["whole_word"] == true +    end + +    test "with adding expires_at", %{conn: conn, user: user} do +      filter = insert(:filter, user: user) +      in_seconds = 600 + +      response = +        conn +        |> put_req_header("content-type", "application/json") +        |> put("/api/v1/filters/#{filter.filter_id}", %{ +          phrase: "nii", +          context: ["public"], +          expires_in: in_seconds, +          irreversible: true +        }) +        |> json_response_and_validate_schema(200) + +      assert response["irreversible"] == true + +      assert response["expires_at"] == +               NaiveDateTime.utc_now() +               |> NaiveDateTime.add(in_seconds) +               |> Pleroma.Web.CommonAPI.Utils.to_masto_date() + +      filter = Filter.get(response["id"], user) + +      id = filter.id + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: id} +      ) + +      assert {:ok, %{id: ^id}} = +               perform_job(PurgeExpiredFilter, %{ +                 filter_id: id +               }) + +      assert Repo.aggregate(Filter, :count, :id) == 0 +    end + +    test "with removing expires_at", %{conn: conn, user: user} do +      response = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/filters", %{ +          phrase: "cofe", +          context: ["home"], +          expires_in: 600 +        }) +        |> json_response_and_validate_schema(200) + +      filter = Filter.get(response["id"], user) + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: filter.id} +      ) + +      response = +        conn +        |> put_req_header("content-type", "application/json") +        |> put("/api/v1/filters/#{filter.filter_id}", %{ +          phrase: "nii", +          context: ["public"], +          expires_in: nil, +          whole_word: true +        }) +        |> json_response_and_validate_schema(200) + +      refute_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: filter.id} +      ) + +      assert response["irreversible"] == false +      assert response["whole_word"] == true +      assert response["expires_at"] == nil +    end + +    test "expires_at is the same in create and update so job is in db", %{conn: conn, user: user} do +      resp1 = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/filters", %{ +          phrase: "cofe", +          context: ["home"], +          expires_in: 600 +        }) +        |> json_response_and_validate_schema(200) + +      filter = Filter.get(resp1["id"], user) + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: filter.id} +      ) + +      job = PurgeExpiredFilter.get_expiration(filter.id) + +      resp2 = +        conn +        |> put_req_header("content-type", "application/json") +        |> put("/api/v1/filters/#{filter.filter_id}", %{ +          phrase: "nii", +          context: ["public"] +        }) +        |> json_response_and_validate_schema(200) + +      updated_filter = Filter.get(resp2["id"], user) + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: updated_filter.id} +      ) + +      after_update = PurgeExpiredFilter.get_expiration(updated_filter.id) + +      assert resp1["expires_at"] == resp2["expires_at"] + +      assert job.scheduled_at == after_update.scheduled_at +    end + +    test "updating expires_at updates oban job too", %{conn: conn, user: user} do +      resp1 = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/filters", %{ +          phrase: "cofe", +          context: ["home"], +          expires_in: 600 +        }) +        |> json_response_and_validate_schema(200) + +      filter = Filter.get(resp1["id"], user) + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: filter.id} +      ) + +      job = PurgeExpiredFilter.get_expiration(filter.id) + +      resp2 = +        conn +        |> put_req_header("content-type", "application/json") +        |> put("/api/v1/filters/#{filter.filter_id}", %{ +          phrase: "nii", +          context: ["public"], +          expires_in: 300 +        }) +        |> json_response_and_validate_schema(200) + +      updated_filter = Filter.get(resp2["id"], user) + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: updated_filter.id} +      ) + +      after_update = PurgeExpiredFilter.get_expiration(updated_filter.id) + +      refute resp1["expires_at"] == resp2["expires_at"] + +      refute job.scheduled_at == after_update.scheduled_at +    end +  end -    new = %Pleroma.Filter{ -      phrase: "nii", -      context: ["home"] -    } +  test "update filter without token", %{conn: conn} do +    filter = insert(:filter) -    conn = +    response =        conn        |> put_req_header("content-type", "application/json") -      |> put("/api/v1/filters/#{query.filter_id}", %{ -        phrase: new.phrase, -        context: new.context +      |> put("/api/v1/filters/#{filter.filter_id}", %{ +        phrase: "nii", +        context: ["public"]        }) +      |> json_response(403) -    assert response = json_response_and_validate_schema(conn, 200) -    assert response["phrase"] == new.phrase -    assert response["context"] == new.context -    assert response["irreversible"] == true -    assert response["whole_word"] == true +    assert response["error"] == "Invalid credentials."    end -  test "delete a filter" do -    %{user: user, conn: conn} = oauth_access(["write:filters"]) - -    query = %Pleroma.Filter{ -      user_id: user.id, -      filter_id: 2, -      phrase: "knight", -      context: ["home"] -    } +  describe "delete a filter" do +    setup do: oauth_access(["write:filters"]) + +    test "common", %{conn: conn, user: user} do +      filter = insert(:filter, user: user) + +      assert conn +             |> delete("/api/v1/filters/#{filter.filter_id}") +             |> json_response_and_validate_schema(200) == %{} + +      assert Repo.all(Filter) == [] +    end + +    test "with expires_at", %{conn: conn, user: user} do +      response = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/filters", %{ +          phrase: "cofe", +          context: ["home"], +          expires_in: 600 +        }) +        |> json_response_and_validate_schema(200) + +      filter = Filter.get(response["id"], user) + +      assert_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: filter.id} +      ) + +      assert conn +             |> delete("/api/v1/filters/#{filter.filter_id}") +             |> json_response_and_validate_schema(200) == %{} + +      refute_enqueued( +        worker: PurgeExpiredFilter, +        args: %{filter_id: filter.id} +      ) + +      assert Repo.all(Filter) == [] +      assert Repo.all(Oban.Job) == [] +    end +  end -    {:ok, filter} = Pleroma.Filter.create(query) +  test "delete a filter without token", %{conn: conn} do +    filter = insert(:filter) -    conn = delete(conn, "/api/v1/filters/#{filter.filter_id}") +    response = +      conn +      |> delete("/api/v1/filters/#{filter.filter_id}") +      |> json_response(403) -    assert json_response_and_validate_schema(conn, 200) == %{} +    assert response["error"] == "Invalid credentials."    end  end diff --git a/test/pleroma/web/mastodon_api/controllers/follow_request_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/follow_request_controller_test.exs index b977b41ae..069ffb3d6 100644 --- a/test/pleroma/web/mastodon_api/controllers/follow_request_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/follow_request_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.FollowRequestControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.User    alias Pleroma.Web.CommonAPI diff --git a/test/pleroma/web/mastodon_api/controllers/instance_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/instance_controller_test.exs index 605df6ed6..b99856659 100644 --- a/test/pleroma/web/mastodon_api/controllers/instance_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/instance_controller_test.exs @@ -1,8 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do +  # TODO: Should not need Cachex    use Pleroma.Web.ConnCase    alias Pleroma.User @@ -46,6 +47,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do      assert result["pleroma"]["metadata"]["federation"]      assert result["pleroma"]["metadata"]["fields_limits"]      assert result["pleroma"]["vapid_public_key"] +    assert result["pleroma"]["stats"]["mau"] == 0      assert email == from_config_email      assert thumbnail == from_config_thumbnail @@ -56,7 +58,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceControllerTest do      user = insert(:user, %{local: true})      user2 = insert(:user, %{local: true}) -    {:ok, _user2} = User.deactivate(user2, !user2.deactivated) +    {:ok, _user2} = User.set_activation(user2, false)      insert(:user, %{local: false, nickname: "u@peer1.com"})      insert(:user, %{local: false, nickname: "u@peer2.com"}) diff --git a/test/pleroma/web/mastodon_api/controllers/list_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/list_controller_test.exs index 091ec006c..28099837e 100644 --- a/test/pleroma/web/mastodon_api/controllers/list_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/list_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.ListControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Repo @@ -55,30 +55,39 @@ defmodule Pleroma.Web.MastodonAPI.ListControllerTest do    test "adding users to a list" do      %{user: user, conn: conn} = oauth_access(["write:lists"])      other_user = insert(:user) +    third_user = insert(:user)      {:ok, list} = Pleroma.List.create("name", user)      assert %{} ==               conn               |> put_req_header("content-type", "application/json") -             |> post("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]}) +             |> post("/api/v1/lists/#{list.id}/accounts", %{ +               "account_ids" => [other_user.id, third_user.id] +             })               |> json_response_and_validate_schema(:ok)      %Pleroma.List{following: following} = Pleroma.List.get(list.id, user) -    assert following == [other_user.follower_address] +    assert length(following) == 2 +    assert other_user.follower_address in following +    assert third_user.follower_address in following    end    test "removing users from a list, body params" do      %{user: user, conn: conn} = oauth_access(["write:lists"])      other_user = insert(:user)      third_user = insert(:user) +    fourth_user = insert(:user)      {:ok, list} = Pleroma.List.create("name", user)      {:ok, list} = Pleroma.List.follow(list, other_user)      {:ok, list} = Pleroma.List.follow(list, third_user) +    {:ok, list} = Pleroma.List.follow(list, fourth_user)      assert %{} ==               conn               |> put_req_header("content-type", "application/json") -             |> delete("/api/v1/lists/#{list.id}/accounts", %{"account_ids" => [other_user.id]}) +             |> delete("/api/v1/lists/#{list.id}/accounts", %{ +               "account_ids" => [other_user.id, fourth_user.id] +             })               |> json_response_and_validate_schema(:ok)      %Pleroma.List{following: following} = Pleroma.List.get(list.id, user) diff --git a/test/pleroma/web/mastodon_api/controllers/marker_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/marker_controller_test.exs index 9f0481120..53aebe8e4 100644 --- a/test/pleroma/web/mastodon_api/controllers/marker_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/marker_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.MarkerControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/web/mastodon_api/controllers/media_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/media_controller_test.exs index d2bd57515..6c8f984d5 100644 --- a/test/pleroma/web/mastodon_api/controllers/media_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/media_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.MediaControllerTest do diff --git a/test/pleroma/web/mastodon_api/controllers/notification_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/notification_controller_test.exs index 9ac8488f6..2615912a8 100644 --- a/test/pleroma/web/mastodon_api/controllers/notification_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/notification_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do @@ -555,24 +555,11 @@ defmodule Pleroma.Web.MastodonAPI.NotificationControllerTest do      assert length(json_response_and_validate_schema(conn, 200)) == 1    end -  @tag capture_log: true    test "see move notifications" do      old_user = insert(:user)      new_user = insert(:user, also_known_as: [old_user.ap_id])      %{user: follower, conn: conn} = oauth_access(["read:notifications"]) -    old_user_url = old_user.ap_id - -    body = -      File.read!("test/fixtures/users_mock/localhost.json") -      |> String.replace("{{nickname}}", old_user.nickname) -      |> Jason.encode!() - -    Tesla.Mock.mock(fn -      %{method: :get, url: ^old_user_url} -> -        %Tesla.Env{status: 200, body: body} -    end) -      User.follow(follower, old_user)      Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)      Pleroma.Tests.ObanHelpers.perform_all() diff --git a/test/pleroma/web/mastodon_api/controllers/poll_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/poll_controller_test.exs index f41de6448..da0a631a9 100644 --- a/test/pleroma/web/mastodon_api/controllers/poll_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/poll_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.PollControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Object    alias Pleroma.Web.CommonAPI @@ -20,7 +20,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do            poll: %{options: ["what Mastodon't", "n't what Mastodoes"], expires_in: 20}          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        conn = get(conn, "/api/v1/polls/#{object.id}") @@ -39,7 +39,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do            visibility: "private"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        conn = get(conn, "/api/v1/polls/#{object.id}") @@ -47,6 +47,78 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do      end    end +  test "own_votes" do +    %{conn: conn} = oauth_access(["write:statuses", "read:statuses"]) + +    other_user = insert(:user) + +    {:ok, activity} = +      CommonAPI.post(other_user, %{ +        status: "A very delicious sandwich", +        poll: %{ +          options: ["Lettuce", "Grilled Bacon", "Tomato"], +          expires_in: 20, +          multiple: true +        } +      }) + +    object = Object.normalize(activity, fetch: false) + +    conn +    |> put_req_header("content-type", "application/json") +    |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 2]}) +    |> json_response_and_validate_schema(200) + +    object = Object.get_by_id(object.id) + +    assert [ +             %{ +               "name" => "Lettuce", +               "replies" => %{"totalItems" => 1, "type" => "Collection"}, +               "type" => "Note" +             }, +             %{ +               "name" => "Grilled Bacon", +               "replies" => %{"totalItems" => 0, "type" => "Collection"}, +               "type" => "Note" +             }, +             %{ +               "name" => "Tomato", +               "replies" => %{"totalItems" => 1, "type" => "Collection"}, +               "type" => "Note" +             } +           ] == object.data["anyOf"] + +    assert %{"replies" => %{"totalItems" => 0}} = +             Enum.find(object.data["anyOf"], fn %{"name" => name} -> name == "Grilled Bacon" end) + +    Enum.each(["Lettuce", "Tomato"], fn title -> +      %{"replies" => %{"totalItems" => total_items}} = +        Enum.find(object.data["anyOf"], fn %{"name" => name} -> name == title end) + +      assert total_items == 1 +    end) + +    assert %{ +             "own_votes" => own_votes, +             "voted" => true +           } = +             conn +             |> get("/api/v1/polls/#{object.id}") +             |> json_response_and_validate_schema(200) + +    assert 0 in own_votes +    assert 2 in own_votes +    # for non authenticated user +    response = +      build_conn() +      |> get("/api/v1/polls/#{object.id}") +      |> json_response_and_validate_schema(200) + +    refute Map.has_key?(response, "own_votes") +    refute Map.has_key?(response, "voted") +  end +    describe "POST /api/v1/polls/:id/votes" do      setup do: oauth_access(["write:statuses"]) @@ -63,14 +135,13 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do            }          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false) -      conn = -        conn -        |> put_req_header("content-type", "application/json") -        |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]}) +      conn +      |> put_req_header("content-type", "application/json") +      |> post("/api/v1/polls/#{object.id}/votes", %{"choices" => [0, 1, 2]}) +      |> json_response_and_validate_schema(200) -      assert json_response_and_validate_schema(conn, 200)        object = Object.get_by_id(object.id)        assert Enum.all?(object.data["anyOf"], fn %{"replies" => %{"totalItems" => total_items}} -> @@ -85,7 +156,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do            poll: %{options: ["Yes", "No"], expires_in: 20}          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert conn               |> put_req_header("content-type", "application/json") @@ -106,7 +177,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do            poll: %{options: ["half empty", "half full"], expires_in: 20}          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert conn               |> put_req_header("content-type", "application/json") @@ -129,7 +200,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do            poll: %{options: ["Yes", "No"], expires_in: 20}          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        conn =          conn @@ -158,7 +229,7 @@ defmodule Pleroma.Web.MastodonAPI.PollControllerTest do            visibility: "private"          }) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        conn =          conn diff --git a/test/pleroma/web/mastodon_api/controllers/report_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/report_controller_test.exs index 6636cff96..fcfc4a48a 100644 --- a/test/pleroma/web/mastodon_api/controllers/report_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/report_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.ReportControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Web.CommonAPI diff --git a/test/pleroma/web/mastodon_api/controllers/scheduled_activity_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/scheduled_activity_controller_test.exs index 1ff871c89..b28e3df56 100644 --- a/test/pleroma/web/mastodon_api/controllers/scheduled_activity_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/scheduled_activity_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do @@ -55,7 +55,7 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do    end    test "updates a scheduled activity" do -    Pleroma.Config.put([ScheduledActivity, :enabled], true) +    clear_config([ScheduledActivity, :enabled], true)      %{user: user, conn: conn} = oauth_access(["write:statuses"])      scheduled_at = Timex.shift(NaiveDateTime.utc_now(), minutes: 60) @@ -103,7 +103,7 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityControllerTest do    end    test "deletes a scheduled activity" do -    Pleroma.Config.put([ScheduledActivity, :enabled], true) +    clear_config([ScheduledActivity, :enabled], true)      %{user: user, conn: conn} = oauth_access(["write:statuses"])      scheduled_at = Timex.shift(NaiveDateTime.utc_now(), minutes: 60) diff --git a/test/pleroma/web/mastodon_api/controllers/search_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/search_controller_test.exs index 1045ab265..1dd0fa3b8 100644 --- a/test/pleroma/web/mastodon_api/controllers/search_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/search_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do @@ -309,7 +309,7 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do          })        capture_log(fn -> -        q = Object.normalize(activity).data["id"] +        q = Object.normalize(activity, fetch: false).data["id"]          results =            conn diff --git a/test/pleroma/web/mastodon_api/controllers/status_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/status_controller_test.exs index 30d542dfa..99ad87d05 100644 --- a/test/pleroma/web/mastodon_api/controllers/status_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/status_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do @@ -7,7 +7,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do    use Oban.Testing, repo: Pleroma.Repo    alias Pleroma.Activity -  alias Pleroma.Config    alias Pleroma.Conversation.Participation    alias Pleroma.Object    alias Pleroma.Repo @@ -29,7 +28,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do      setup do: oauth_access(["write:statuses"])      test "posting a status does not increment reblog_count when relaying", %{conn: conn} do -      Config.put([:instance, :federating], true) +      clear_config([:instance, :federating], true)        Config.get([:instance, :allow_relay], true)        response = @@ -67,10 +66,6 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do            "sensitive" => "0"          }) -      {:ok, ttl} = Cachex.ttl(:idempotency_cache, idempotency_key) -      # Six hours -      assert ttl > :timer.seconds(6 * 60 * 60 - 1) -        assert %{"content" => "cofe", "id" => id, "spoiler_text" => "2hu", "sensitive" => false} =                 json_response_and_validate_schema(conn_one, 200) @@ -155,8 +150,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do      end      test "Get MRF reason when posting a status is rejected by one", %{conn: conn} do -      Config.put([:mrf_keyword, :reject], ["GNO"]) -      Config.put([:mrf, :policies], [Pleroma.Web.ActivityPub.MRF.KeywordPolicy]) +      clear_config([:mrf_keyword, :reject], ["GNO"]) +      clear_config([:mrf, :policies], [Pleroma.Web.ActivityPub.MRF.KeywordPolicy])        assert %{"error" => "[KeywordPolicy] Matches with rejected keyword"} =                 conn @@ -268,6 +263,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do        fake_conn =          conn +        |> assign(:user, refresh_record(conn.assigns.user))          |> put_req_header("content-type", "application/json")          |> post("/api/v1/statuses", %{            "status" => @@ -361,6 +357,69 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do        assert activity.data["to"] == [user2.ap_id]        assert activity.data["cc"] == []      end + +    test "discloses application metadata when enabled" do +      user = insert(:user, disclose_client: true) +      %{user: _user, token: token, conn: conn} = oauth_access(["write:statuses"], user: user) + +      %Pleroma.Web.OAuth.Token{ +        app: %Pleroma.Web.OAuth.App{ +          client_name: app_name, +          website: app_website +        } +      } = token + +      result = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/statuses", %{ +          "status" => "cofe is my copilot" +        }) + +      assert %{ +               "content" => "cofe is my copilot" +             } = json_response_and_validate_schema(result, 200) + +      activity = result.assigns.activity.id + +      result = +        conn +        |> get("api/v1/statuses/#{activity}") + +      assert %{ +               "content" => "cofe is my copilot", +               "application" => %{ +                 "name" => ^app_name, +                 "website" => ^app_website +               } +             } = json_response_and_validate_schema(result, 200) +    end + +    test "hides application metadata when disabled" do +      user = insert(:user, disclose_client: false) +      %{user: _user, token: _token, conn: conn} = oauth_access(["write:statuses"], user: user) + +      result = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/statuses", %{ +          "status" => "club mate is my wingman" +        }) + +      assert %{"content" => "club mate is my wingman"} = +               json_response_and_validate_schema(result, 200) + +      activity = result.assigns.activity.id + +      result = +        conn +        |> get("api/v1/statuses/#{activity}") + +      assert %{ +               "content" => "club mate is my wingman", +               "application" => nil +             } = json_response_and_validate_schema(result, 200) +    end    end    describe "posting scheduled statuses" do @@ -387,6 +446,31 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do        assert [] == Repo.all(Activity)      end +    test "with expiration" do +      %{conn: conn} = oauth_access(["write:statuses", "read:statuses"]) + +      scheduled_at = +        NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(6), :millisecond) +        |> NaiveDateTime.to_iso8601() +        |> Kernel.<>("Z") + +      assert %{"id" => status_id, "params" => %{"expires_in" => 300}} = +               conn +               |> put_req_header("content-type", "application/json") +               |> post("/api/v1/statuses", %{ +                 "status" => "scheduled", +                 "scheduled_at" => scheduled_at, +                 "expires_in" => 300 +               }) +               |> json_response_and_validate_schema(200) + +      assert %{"id" => ^status_id, "params" => %{"expires_in" => 300}} = +               conn +               |> put_req_header("content-type", "application/json") +               |> get("/api/v1/scheduled_statuses/#{status_id}") +               |> json_response_and_validate_schema(200) +    end +      test "ignores nil values", %{conn: conn} do        conn =          conn @@ -520,7 +604,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do               end)        assert NaiveDateTime.diff(NaiveDateTime.from_iso8601!(response["poll"]["expires_at"]), time) in 420..430 -      refute response["poll"]["expred"] +      assert response["poll"]["expired"] == false        question = Object.get_by_id(response["poll"]["id"]) @@ -596,6 +680,44 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do        %{"error" => error} = json_response_and_validate_schema(conn, 422)        assert error == "Expiration date is too far in the future"      end + +    test "scheduled poll", %{conn: conn} do +      clear_config([ScheduledActivity, :enabled], true) + +      scheduled_at = +        NaiveDateTime.add(NaiveDateTime.utc_now(), :timer.minutes(6), :millisecond) +        |> NaiveDateTime.to_iso8601() +        |> Kernel.<>("Z") + +      %{"id" => scheduled_id} = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/statuses", %{ +          "status" => "very cool poll", +          "poll" => %{ +            "options" => ~w(a b c), +            "expires_in" => 420 +          }, +          "scheduled_at" => scheduled_at +        }) +        |> json_response_and_validate_schema(200) + +      assert {:ok, %{id: activity_id}} = +               perform_job(Pleroma.Workers.ScheduledActivityWorker, %{ +                 activity_id: scheduled_id +               }) + +      assert Repo.all(Oban.Job) == [] + +      object = +        Activity +        |> Repo.get(activity_id) +        |> Object.normalize() + +      assert object.data["content"] == "very cool poll" +      assert object.data["type"] == "Question" +      assert length(object.data["oneOf"]) == 3 +    end    end    test "get a status" do @@ -804,7 +926,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do      test "when you created it" do        %{user: author, conn: conn} = oauth_access(["write:statuses"])        activity = insert(:note_activity, user: author) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        content = object.data["content"]        source = object.data["source"] @@ -958,6 +1080,23 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do        assert to_string(activity.id) == id      end + +    test "author can reblog own private status", %{conn: conn, user: user} do +      {:ok, activity} = CommonAPI.post(user, %{status: "cofe", visibility: "private"}) + +      conn = +        conn +        |> put_req_header("content-type", "application/json") +        |> post("/api/v1/statuses/#{activity.id}/reblog") + +      assert %{ +               "reblog" => %{"id" => id, "reblogged" => true, "reblogs_count" => 1}, +               "reblogged" => true, +               "visibility" => "private" +             } = json_response_and_validate_schema(conn, 200) + +      assert to_string(activity.id) == id +    end    end    describe "unreblogging" do @@ -1070,20 +1209,27 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do      setup do: clear_config([:instance, :max_pinned_statuses], 1)      test "pin status", %{conn: conn, user: user, activity: activity} do -      id_str = to_string(activity.id) +      id = activity.id -      assert %{"id" => ^id_str, "pinned" => true} = +      assert %{"id" => ^id, "pinned" => true} =                 conn                 |> put_req_header("content-type", "application/json")                 |> post("/api/v1/statuses/#{activity.id}/pin")                 |> json_response_and_validate_schema(200) -      assert [%{"id" => ^id_str, "pinned" => true}] = +      assert [%{"id" => ^id, "pinned" => true}] =                 conn                 |> get("/api/v1/accounts/#{user.id}/statuses?pinned=true")                 |> json_response_and_validate_schema(200)      end +    test "non authenticated user", %{activity: activity} do +      assert build_conn() +             |> put_req_header("content-type", "application/json") +             |> post("/api/v1/statuses/#{activity.id}/pin") +             |> json_response(403) == %{"error" => "Invalid credentials."} +    end +      test "/pin: returns 400 error when activity is not public", %{conn: conn, user: user} do        {:ok, dm} = CommonAPI.post(user, %{status: "test", visibility: "direct"}) @@ -1092,7 +1238,18 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do          |> put_req_header("content-type", "application/json")          |> post("/api/v1/statuses/#{dm.id}/pin") -      assert json_response_and_validate_schema(conn, 400) == %{"error" => "Could not pin"} +      assert json_response_and_validate_schema(conn, 422) == %{ +               "error" => "Non-public status cannot be pinned" +             } +    end + +    test "pin by another user", %{activity: activity} do +      %{conn: conn} = oauth_access(["write:accounts"]) + +      assert conn +             |> put_req_header("content-type", "application/json") +             |> post("/api/v1/statuses/#{activity.id}/pin") +             |> json_response(422) == %{"error" => "Someone else's status cannot be pinned"}      end      test "unpin status", %{conn: conn, user: user, activity: activity} do @@ -1113,13 +1270,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do                 |> json_response_and_validate_schema(200)      end -    test "/unpin: returns 400 error when activity is not exist", %{conn: conn} do -      conn = -        conn -        |> put_req_header("content-type", "application/json") -        |> post("/api/v1/statuses/1/unpin") - -      assert json_response_and_validate_schema(conn, 400) == %{"error" => "Could not unpin"} +    test "/unpin: returns 404 error when activity doesn't exist", %{conn: conn} do +      assert conn +             |> put_req_header("content-type", "application/json") +             |> post("/api/v1/statuses/1/unpin") +             |> json_response_and_validate_schema(404) == %{"error" => "Record not found"}      end      test "max pinned statuses", %{conn: conn, user: user, activity: activity_one} do @@ -1191,7 +1346,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do    describe "cards" do      setup do -      Config.put([:rich_media, :enabled], true) +      clear_config([:rich_media, :enabled], true)        oauth_access(["read:statuses"])      end @@ -1378,7 +1533,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do      activity = Activity.get_by_id_with_object(id) -    assert Object.normalize(activity).data["inReplyTo"] == Object.normalize(replied_to).data["id"] +    assert Object.normalize(activity, fetch: false).data["inReplyTo"] == +             Object.normalize(replied_to, fetch: false).data["id"] +      assert Activity.get_in_reply_to_activity(activity).id == replied_to.id      # Reblog from the third user diff --git a/test/pleroma/web/mastodon_api/controllers/subscription_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/subscription_controller_test.exs index 5ef39bdb2..5a3f93d2d 100644 --- a/test/pleroma/web/mastodon_api/controllers/subscription_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/subscription_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory diff --git a/test/pleroma/web/mastodon_api/controllers/suggestion_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/suggestion_controller_test.exs index 7f08e187c..168966fc9 100644 --- a/test/pleroma/web/mastodon_api/controllers/suggestion_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/suggestion_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    setup do: oauth_access(["read"]) diff --git a/test/pleroma/web/mastodon_api/controllers/timeline_controller_test.exs b/test/pleroma/web/mastodon_api/controllers/timeline_controller_test.exs index 655e35ac6..cc409451c 100644 --- a/test/pleroma/web/mastodon_api/controllers/timeline_controller_test.exs +++ b/test/pleroma/web/mastodon_api/controllers/timeline_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do @@ -90,6 +90,65 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do                 }               ] = result      end + +    test "filtering", %{conn: conn, user: user} do +      local_user = insert(:user) +      {:ok, user, local_user} = User.follow(user, local_user) +      {:ok, local_activity} = CommonAPI.post(local_user, %{status: "Status"}) +      with_media = create_with_media_activity(local_user) + +      remote_user = insert(:user, local: false) +      {:ok, _user, remote_user} = User.follow(user, remote_user) +      remote_activity = create_remote_activity(remote_user) + +      without_filter_ids = +        conn +        |> get("/api/v1/timelines/home") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      assert local_activity.id in without_filter_ids +      assert remote_activity.id in without_filter_ids +      assert with_media.id in without_filter_ids + +      only_local_ids = +        conn +        |> get("/api/v1/timelines/home?local=true") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      assert local_activity.id in only_local_ids +      refute remote_activity.id in only_local_ids +      assert with_media.id in only_local_ids + +      only_local_media_ids = +        conn +        |> get("/api/v1/timelines/home?local=true&only_media=true") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      refute local_activity.id in only_local_media_ids +      refute remote_activity.id in only_local_media_ids +      assert with_media.id in only_local_media_ids + +      remote_ids = +        conn +        |> get("/api/v1/timelines/home?remote=true") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      refute local_activity.id in remote_ids +      assert remote_activity.id in remote_ids +      refute with_media.id in remote_ids + +      assert conn +             |> get("/api/v1/timelines/home?remote=true&only_media=true") +             |> json_response_and_validate_schema(200) == [] + +      assert conn +             |> get("/api/v1/timelines/home?remote=true&local=true") +             |> json_response_and_validate_schema(200) == [] +    end    end    describe "public" do @@ -98,27 +157,80 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do        user = insert(:user)        {:ok, activity} = CommonAPI.post(user, %{status: "test"}) +      with_media = create_with_media_activity(user) -      _activity = insert(:note_activity, local: false) +      remote = insert(:note_activity, local: false) -      conn = get(conn, "/api/v1/timelines/public?local=False") +      assert conn +             |> get("/api/v1/timelines/public?local=False") +             |> json_response_and_validate_schema(:ok) +             |> length == 3 -      assert length(json_response_and_validate_schema(conn, :ok)) == 2 +      local_ids = +        conn +        |> get("/api/v1/timelines/public?local=True") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) -      conn = get(build_conn(), "/api/v1/timelines/public?local=True") +      assert activity.id in local_ids +      assert with_media.id in local_ids +      refute remote.id in local_ids -      assert [%{"content" => "test"}] = json_response_and_validate_schema(conn, :ok) +      local_ids = +        conn +        |> get("/api/v1/timelines/public?local=True") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      assert activity.id in local_ids +      assert with_media.id in local_ids +      refute remote.id in local_ids + +      local_ids = +        conn +        |> get("/api/v1/timelines/public?local=True&only_media=true") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      refute activity.id in local_ids +      assert with_media.id in local_ids +      refute remote.id in local_ids + +      local_ids = +        conn +        |> get("/api/v1/timelines/public?local=1") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      assert activity.id in local_ids +      assert with_media.id in local_ids +      refute remote.id in local_ids + +      remote_id = remote.id + +      assert [%{"id" => ^remote_id}] = +               conn +               |> get("/api/v1/timelines/public?remote=true") +               |> json_response_and_validate_schema(:ok) -      conn = get(build_conn(), "/api/v1/timelines/public?local=1") +      with_media_id = with_media.id -      assert [%{"content" => "test"}] = json_response_and_validate_schema(conn, :ok) +      assert [%{"id" => ^with_media_id}] = +               conn +               |> get("/api/v1/timelines/public?only_media=true") +               |> json_response_and_validate_schema(:ok) + +      assert conn +             |> get("/api/v1/timelines/public?remote=true&only_media=true") +             |> json_response_and_validate_schema(:ok) == []        # does not contain repeats        {:ok, _} = CommonAPI.repeat(activity.id, user) -      conn = get(build_conn(), "/api/v1/timelines/public?local=true") - -      assert [_] = json_response_and_validate_schema(conn, :ok) +      assert [_, _] = +               conn +               |> get("/api/v1/timelines/public?local=true") +               |> json_response_and_validate_schema(:ok)      end      test "the public timeline includes only public statuses for an authenticated user" do @@ -544,6 +656,77 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do                 }               ] = result      end + +    test "filtering", %{user: user, conn: conn} do +      {:ok, list} = Pleroma.List.create("name", user) + +      local_user = insert(:user) +      {:ok, local_activity} = CommonAPI.post(local_user, %{status: "Marisa is stupid."}) +      with_media = create_with_media_activity(local_user) +      {:ok, list} = Pleroma.List.follow(list, local_user) + +      remote_user = insert(:user, local: false) +      remote_activity = create_remote_activity(remote_user) +      {:ok, list} = Pleroma.List.follow(list, remote_user) + +      all_ids = +        conn +        |> get("/api/v1/timelines/list/#{list.id}") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      assert local_activity.id in all_ids +      assert with_media.id in all_ids +      assert remote_activity.id in all_ids + +      only_local_ids = +        conn +        |> get("/api/v1/timelines/list/#{list.id}?local=true") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      assert local_activity.id in only_local_ids +      assert with_media.id in only_local_ids +      refute remote_activity.id in only_local_ids + +      only_local_media_ids = +        conn +        |> get("/api/v1/timelines/list/#{list.id}?local=true&only_media=true") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      refute local_activity.id in only_local_media_ids +      assert with_media.id in only_local_media_ids +      refute remote_activity.id in only_local_media_ids + +      remote_ids = +        conn +        |> get("/api/v1/timelines/list/#{list.id}?remote=true") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      refute local_activity.id in remote_ids +      refute with_media.id in remote_ids +      assert remote_activity.id in remote_ids + +      assert conn +             |> get("/api/v1/timelines/list/#{list.id}?remote=true&only_media=true") +             |> json_response_and_validate_schema(200) == [] + +      only_media_ids = +        conn +        |> get("/api/v1/timelines/list/#{list.id}?only_media=true") +        |> json_response_and_validate_schema(200) +        |> Enum.map(& &1["id"]) + +      refute local_activity.id in only_media_ids +      assert with_media.id in only_media_ids +      refute remote_activity.id in only_media_ids + +      assert conn +             |> get("/api/v1/timelines/list/#{list.id}?only_media=true&local=true&remote=true") +             |> json_response_and_validate_schema(200) == [] +    end    end    describe "hashtag" do @@ -554,19 +737,85 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do        following = insert(:user)        {:ok, activity} = CommonAPI.post(following, %{status: "test #2hu"}) +      with_media = create_with_media_activity(following) -      nconn = get(conn, "/api/v1/timelines/tag/2hu") +      remote = insert(:user, local: false) +      remote_activity = create_remote_activity(remote) -      assert [%{"id" => id}] = json_response_and_validate_schema(nconn, :ok) +      all_ids = +        conn +        |> get("/api/v1/timelines/tag/2hu") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) -      assert id == to_string(activity.id) +      assert activity.id in all_ids +      assert with_media.id in all_ids +      assert remote_activity.id in all_ids        # works for different capitalization too -      nconn = get(conn, "/api/v1/timelines/tag/2HU") +      all_ids = +        conn +        |> get("/api/v1/timelines/tag/2HU") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) -      assert [%{"id" => id}] = json_response_and_validate_schema(nconn, :ok) +      assert activity.id in all_ids +      assert with_media.id in all_ids +      assert remote_activity.id in all_ids -      assert id == to_string(activity.id) +      local_ids = +        conn +        |> get("/api/v1/timelines/tag/2hu?local=true") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      assert activity.id in local_ids +      assert with_media.id in local_ids +      refute remote_activity.id in local_ids + +      remote_ids = +        conn +        |> get("/api/v1/timelines/tag/2hu?remote=true") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      refute activity.id in remote_ids +      refute with_media.id in remote_ids +      assert remote_activity.id in remote_ids + +      media_ids = +        conn +        |> get("/api/v1/timelines/tag/2hu?only_media=true") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      refute activity.id in media_ids +      assert with_media.id in media_ids +      refute remote_activity.id in media_ids + +      media_local_ids = +        conn +        |> get("/api/v1/timelines/tag/2hu?only_media=true&local=true") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      refute activity.id in media_local_ids +      assert with_media.id in media_local_ids +      refute remote_activity.id in media_local_ids + +      ids = +        conn +        |> get("/api/v1/timelines/tag/2hu?only_media=true&local=true&remote=true") +        |> json_response_and_validate_schema(:ok) +        |> Enum.map(& &1["id"]) + +      refute activity.id in ids +      refute with_media.id in ids +      refute remote_activity.id in ids + +      assert conn +             |> get("/api/v1/timelines/tag/2hu?only_media=true&remote=true") +             |> json_response_and_validate_schema(:ok) == []      end      test "multi-hashtag timeline", %{conn: conn} do @@ -726,4 +975,37 @@ defmodule Pleroma.Web.MastodonAPI.TimelineControllerTest do        ensure_authenticated_access(base_uri)      end    end + +  defp create_remote_activity(user) do +    obj = +      insert(:note, %{ +        data: %{ +          "to" => [ +            "https://www.w3.org/ns/activitystreams#Public", +            User.ap_followers(user) +          ] +        }, +        user: user +      }) + +    insert(:note_activity, %{ +      note: obj, +      recipients: [ +        "https://www.w3.org/ns/activitystreams#Public", +        User.ap_followers(user) +      ], +      user: user, +      local: false +    }) +  end + +  defp create_with_media_activity(user) do +    obj = insert(:attachment_note, user: user) + +    insert(:note_activity, %{ +      note: obj, +      recipients: ["https://www.w3.org/ns/activitystreams#Public", User.ap_followers(user)], +      user: user +    }) +  end  end diff --git a/test/pleroma/web/mastodon_api/masto_fe_controller_test.exs b/test/pleroma/web/mastodon_api/masto_fe_controller_test.exs index b9cd050df..ea66c708f 100644 --- a/test/pleroma/web/mastodon_api/masto_fe_controller_test.exs +++ b/test/pleroma/web/mastodon_api/masto_fe_controller_test.exs @@ -1,11 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.MastoFEControllerTest do    use Pleroma.Web.ConnCase -  alias Pleroma.Config    alias Pleroma.User    import Pleroma.Factory @@ -55,7 +54,7 @@ defmodule Pleroma.Web.MastodonAPI.MastoFEControllerTest do        conn: conn,        path: path      } do -      Config.put([:instance, :public], false) +      clear_config([:instance, :public], false)        conn = get(conn, path) diff --git a/test/pleroma/web/mastodon_api/mastodon_api_controller_test.exs b/test/pleroma/web/mastodon_api/mastodon_api_controller_test.exs index bb4bc4396..c6332bd3e 100644 --- a/test/pleroma/web/mastodon_api/mastodon_api_controller_test.exs +++ b/test/pleroma/web/mastodon_api/mastodon_api_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    describe "empty_array/2 (stubs)" do      test "GET /api/v1/accounts/:id/identity_proofs" do diff --git a/test/pleroma/web/mastodon_api/mastodon_api_test.exs b/test/pleroma/web/mastodon_api/mastodon_api_test.exs index 687fe5585..402bfd76f 100644 --- a/test/pleroma/web/mastodon_api/mastodon_api_test.exs +++ b/test/pleroma/web/mastodon_api/mastodon_api_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.MastodonAPITest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Notification    alias Pleroma.ScheduledActivity @@ -16,7 +16,7 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPITest do    describe "follow/3" do      test "returns error when followed user is deactivated" do        follower = insert(:user) -      user = insert(:user, local: true, deactivated: true) +      user = insert(:user, local: true, is_active: false)        assert {:error, _error} = MastodonAPI.follow(follower, user)      end diff --git a/test/pleroma/web/mastodon_api/update_credentials_test.exs b/test/pleroma/web/mastodon_api/update_credentials_test.exs index ed1921c91..cfbe6cf0e 100644 --- a/test/pleroma/web/mastodon_api/update_credentials_test.exs +++ b/test/pleroma/web/mastodon_api/update_credentials_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.UpdateCredentialsTest do @@ -11,8 +11,6 @@ defmodule Pleroma.Web.MastodonAPI.UpdateCredentialsTest do    import Mock    import Pleroma.Factory -  setup do: clear_config([:instance, :max_account_fields]) -    describe "updating credentials" do      setup do: oauth_access(["write:accounts"])      setup :request_content_type @@ -220,6 +218,25 @@ defmodule Pleroma.Web.MastodonAPI.UpdateCredentialsTest do        assert update_activity.data["object"]["name"] == "markorepairs"      end +    test "updates the user's AKAs", %{conn: conn} do +      conn = +        patch(conn, "/api/v1/accounts/update_credentials", %{ +          "also_known_as" => ["https://mushroom.kingdom/users/mario"] +        }) + +      assert user_data = json_response_and_validate_schema(conn, 200) +      assert user_data["pleroma"]["also_known_as"] == ["https://mushroom.kingdom/users/mario"] +    end + +    test "doesn't update non-url akas", %{conn: conn} do +      conn = +        patch(conn, "/api/v1/accounts/update_credentials", %{ +          "also_known_as" => ["aReallyCoolGuy"] +        }) + +      assert json_response_and_validate_schema(conn, 403) +    end +      test "updates the user's avatar", %{user: user, conn: conn} do        new_avatar = %Plug.Upload{          content_type: "image/jpeg", @@ -446,7 +463,7 @@ defmodule Pleroma.Web.MastodonAPI.UpdateCredentialsTest do                 |> patch("/api/v1/accounts/update_credentials", %{"fields_attributes" => fields})                 |> json_response_and_validate_schema(403) -      Pleroma.Config.put([:instance, :max_account_fields], 1) +      clear_config([:instance, :max_account_fields], 1)        fields = [          %{"name" => "foo", "value" => "bar"}, diff --git a/test/pleroma/web/mastodon_api/views/account_view_test.exs b/test/pleroma/web/mastodon_api/views/account_view_test.exs index 8c77f14d4..5373a17c3 100644 --- a/test/pleroma/web/mastodon_api/views/account_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/account_view_test.exs @@ -1,11 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.AccountViewTest do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.User    alias Pleroma.UserRelationship    alias Pleroma.Web.CommonAPI @@ -35,7 +34,8 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do            "<script src=\"invalid-html\"></script><span>valid html</span>. a<br>b<br/>c<br >d<br />f '&<>\"",          inserted_at: ~N[2017-08-15 15:47:06.597036],          emoji: %{"karjalanpiirakka" => "/file.png"}, -        raw_bio: "valid html. a\nb\nc\nd\nf '&<>\"" +        raw_bio: "valid html. a\nb\nc\nd\nf '&<>\"", +        also_known_as: ["https://shitposter.zone/users/shp"]        })      expected = %{ @@ -73,11 +73,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do          },          fields: []        }, +      fqn: "shp@shitposter.club",        pleroma: %{          ap_id: user.ap_id, +        also_known_as: ["https://shitposter.zone/users/shp"],          background_image: "https://example.com/images/asuka_hospital.png",          favicon: nil, -        confirmation_pending: false, +        is_confirmed: true,          tags: [],          is_admin: false,          is_moderator: false, @@ -171,11 +173,13 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do          },          fields: []        }, +      fqn: "shp@shitposter.club",        pleroma: %{          ap_id: user.ap_id, +        also_known_as: [],          background_image: nil,          favicon: nil, -        confirmation_pending: false, +        is_confirmed: true,          tags: [],          is_admin: false,          is_moderator: false, @@ -208,7 +212,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do    test "Represent a deactivated user for an admin" do      admin = insert(:user, is_admin: true) -    deactivated_user = insert(:user, deactivated: true) +    deactivated_user = insert(:user, is_active: false)      represented = AccountView.render("show.json", %{user: deactivated_user, for: admin})      assert represented[:pleroma][:deactivated] == true    end @@ -553,7 +557,7 @@ defmodule Pleroma.Web.MastodonAPI.AccountViewTest do        )      with media_preview_enabled <- [false, true] do -      Config.put([:media_preview_proxy, :enabled], media_preview_enabled) +      clear_config([:media_preview_proxy, :enabled], media_preview_enabled)        AccountView.render("show.json", %{user: user, skip_visibility_check: true})        |> Enum.all?(fn diff --git a/test/pleroma/web/mastodon_api/views/conversation_view_test.exs b/test/pleroma/web/mastodon_api/views/conversation_view_test.exs index 20c10ba3d..9639e95d2 100644 --- a/test/pleroma/web/mastodon_api/views/conversation_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/conversation_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.ConversationViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Conversation.Participation    alias Pleroma.Web.CommonAPI diff --git a/test/pleroma/web/mastodon_api/views/list_view_test.exs b/test/pleroma/web/mastodon_api/views/list_view_test.exs index ca99242cb..a62495ebb 100644 --- a/test/pleroma/web/mastodon_api/views/list_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/list_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.ListViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.MastodonAPI.ListView diff --git a/test/pleroma/web/mastodon_api/views/marker_view_test.exs b/test/pleroma/web/mastodon_api/views/marker_view_test.exs index 48a0a6d33..8d8c16f6c 100644 --- a/test/pleroma/web/mastodon_api/views/marker_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/marker_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.MarkerViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.MastodonAPI.MarkerView    import Pleroma.Factory diff --git a/test/pleroma/web/mastodon_api/views/notification_view_test.exs b/test/pleroma/web/mastodon_api/views/notification_view_test.exs index 9de11a87e..496a688d1 100644 --- a/test/pleroma/web/mastodon_api/views/notification_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/notification_view_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do @@ -44,7 +44,7 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do      {:ok, [notification]} = Notification.create_notifications(activity) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      chat = Chat.get(recipient.id, user.ap_id)      cm_ref = MessageReference.for_chat_and_object(chat, object) @@ -144,24 +144,11 @@ defmodule Pleroma.Web.MastodonAPI.NotificationViewTest do      refute Repo.one(Notification)    end -  @tag capture_log: true    test "Move notification" do      old_user = insert(:user)      new_user = insert(:user, also_known_as: [old_user.ap_id])      follower = insert(:user) -    old_user_url = old_user.ap_id - -    body = -      File.read!("test/fixtures/users_mock/localhost.json") -      |> String.replace("{{nickname}}", old_user.nickname) -      |> Jason.encode!() - -    Tesla.Mock.mock(fn -      %{method: :get, url: ^old_user_url} -> -        %Tesla.Env{status: 200, body: body} -    end) -      User.follow(follower, old_user)      Pleroma.Web.ActivityPub.ActivityPub.move(old_user, new_user)      Pleroma.Tests.ObanHelpers.perform_all() diff --git a/test/pleroma/web/mastodon_api/views/poll_view_test.exs b/test/pleroma/web/mastodon_api/views/poll_view_test.exs index c655ca438..224b26cb9 100644 --- a/test/pleroma/web/mastodon_api/views/poll_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/poll_view_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.PollViewTest do @@ -29,7 +29,7 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do          }        }) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      expected = %{        emojis: [], @@ -42,7 +42,6 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do          %{title: "yes", votes_count: 0},          %{title: "why are you even asking?", votes_count: 0}        ], -      voted: false,        votes_count: 0,        voters_count: 0      } @@ -72,7 +71,7 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do      voter = insert(:user) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      {:ok, _votes, object} = CommonAPI.vote(voter, object, [0, 1]) @@ -98,7 +97,7 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do          }        }) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert %{emojis: [%{shortcode: "blank"}]} = PollView.render("show.json", %{object: object})    end @@ -117,19 +116,21 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do          }        }) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      {:ok, _, object} = CommonAPI.vote(other_user, object, [1, 2])      result = PollView.render("show.json", %{object: object, for: other_user})      assert result[:voted] == true +    assert 1 in result[:own_votes] +    assert 2 in result[:own_votes]      assert Enum.at(result[:options], 1)[:votes_count] == 1      assert Enum.at(result[:options], 2)[:votes_count] == 1    end    test "does not crash on polls with no end date" do -    object = Object.normalize("https://skippers-bin.com/notes/7x9tmrp97i") +    object = Object.normalize("https://skippers-bin.com/notes/7x9tmrp97i", fetch: true)      result = PollView.render("show.json", %{object: object})      assert result[:expires_at] == nil @@ -153,7 +154,7 @@ defmodule Pleroma.Web.MastodonAPI.PollViewTest do          }        }) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert %{               options: [ diff --git a/test/pleroma/web/mastodon_api/views/scheduled_activity_view_test.exs b/test/pleroma/web/mastodon_api/views/scheduled_activity_view_test.exs index 04f73f5a0..e323f3a1f 100644 --- a/test/pleroma/web/mastodon_api/views/scheduled_activity_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/scheduled_activity_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.ScheduledActivityViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.ScheduledActivity    alias Pleroma.Web.ActivityPub.ActivityPub    alias Pleroma.Web.CommonAPI @@ -58,7 +58,8 @@ defmodule Pleroma.Web.MastodonAPI.ScheduledActivityViewTest do          sensitive: true,          spoiler_text: "spoiler",          text: "hi", -        visibility: "unlisted" +        visibility: "unlisted", +        expires_in: nil        },        scheduled_at: Utils.to_masto_date(scheduled_activity.scheduled_at)      } diff --git a/test/pleroma/web/mastodon_api/views/status_view_test.exs b/test/pleroma/web/mastodon_api/views/status_view_test.exs index f2a7469ed..fbea25079 100644 --- a/test/pleroma/web/mastodon_api/views/status_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/status_view_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.StatusViewTest do @@ -61,7 +61,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do      {:ok, activity} = CommonAPI.post(user, %{status: "yo"})      activity -    |> Object.normalize(false) +    |> Object.normalize(fetch: false)      |> Object.update_data(%{"reactions" => %{"☕" => [user.ap_id], "x" => 1}})      activity = Activity.get_by_id(activity.id) @@ -160,7 +160,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do      {:ok, activity} = CommonAPI.post(user, %{status: "Hey @shp!", visibility: "direct"})      Repo.delete(user) -    Cachex.clear(:user_cache) +    User.invalidate_cache(user)      finger_url =        "https://localhost/.well-known/webfinger?resource=acct:#{user.nickname}@localhost" @@ -194,7 +194,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do        |> Ecto.Changeset.change(%{ap_id: "#{user.ap_id}/extension/#{user.nickname}"})        |> Repo.update() -    Cachex.clear(:user_cache) +    User.invalidate_cache(user)      result = StatusView.render("show.json", activity: activity) @@ -204,7 +204,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do    test "a note with null content" do      note = insert(:note_activity) -    note_object = Object.normalize(note) +    note_object = Object.normalize(note, fetch: false)      data =        note_object.data @@ -223,7 +223,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do    test "a note activity" do      note = insert(:note_activity) -    object_data = Object.normalize(note).data +    object_data = Object.normalize(note, fetch: false).data      user = User.get_cached_by_ap_id(note.data["actor"])      convo_id = Utils.context_to_conversation_id(object_data["context"]) @@ -262,14 +262,11 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do        mentions: [],        tags: [          %{ -          name: "#{object_data["tag"]}", -          url: "/tag/#{object_data["tag"]}" +          name: "#{hd(object_data["tag"])}", +          url: "http://localhost:4001/tag/#{hd(object_data["tag"])}"          }        ], -      application: %{ -        name: "Web", -        website: nil -      }, +      application: nil,        language: nil,        emojis: [          %{ @@ -289,7 +286,8 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do          direct_conversation_id: nil,          thread_muted: false,          emoji_reactions: [], -        parent_visible: false +        parent_visible: false, +        pinned_at: nil        }      } @@ -585,9 +583,9 @@ defmodule Pleroma.Web.MastodonAPI.StatusViewTest do        ]        assert StatusView.build_tags(object_tags) == [ -               %{name: "fediverse", url: "/tag/fediverse"}, -               %{name: "mastodon", url: "/tag/mastodon"}, -               %{name: "nextcloud", url: "/tag/nextcloud"} +               %{name: "fediverse", url: "http://localhost:4001/tag/fediverse"}, +               %{name: "mastodon", url: "http://localhost:4001/tag/mastodon"}, +               %{name: "nextcloud", url: "http://localhost:4001/tag/nextcloud"}               ]      end    end diff --git a/test/pleroma/web/mastodon_api/views/subscription_view_test.exs b/test/pleroma/web/mastodon_api/views/subscription_view_test.exs index 981524c0e..04b440389 100644 --- a/test/pleroma/web/mastodon_api/views/subscription_view_test.exs +++ b/test/pleroma/web/mastodon_api/views/subscription_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MastodonAPI.SubscriptionViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.MastodonAPI.SubscriptionView, as: View    alias Pleroma.Web.Push diff --git a/test/pleroma/web/media_proxy/invalidation/http_test.exs b/test/pleroma/web/media_proxy/invalidation/http_test.exs index 13d081325..a15103c89 100644 --- a/test/pleroma/web/media_proxy/invalidation/http_test.exs +++ b/test/pleroma/web/media_proxy/invalidation/http_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MediaProxy.Invalidation.HttpTest do @@ -9,10 +9,6 @@ defmodule Pleroma.Web.MediaProxy.Invalidation.HttpTest do    import ExUnit.CaptureLog    import Tesla.Mock -  setup do -    on_exit(fn -> Cachex.clear(:banned_urls_cache) end) -  end -    test "logs hasn't error message when request is valid" do      mock(fn        %{method: :purge, url: "http://example.com/media/example.jpg"} -> diff --git a/test/pleroma/web/media_proxy/invalidation/script_test.exs b/test/pleroma/web/media_proxy/invalidation/script_test.exs index 692cbb2df..e9629b72b 100644 --- a/test/pleroma/web/media_proxy/invalidation/script_test.exs +++ b/test/pleroma/web/media_proxy/invalidation/script_test.exs @@ -1,18 +1,14 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MediaProxy.Invalidation.ScriptTest do -  use ExUnit.Case +  use ExUnit.Case, async: true    alias Pleroma.Web.MediaProxy.Invalidation    import ExUnit.CaptureLog -  setup do -    on_exit(fn -> Cachex.clear(:banned_urls_cache) end) -  end - -  test "it logger error when script not found" do +  test "it logs error when script is not found" do      assert capture_log(fn ->               assert Invalidation.Script.purge(                        ["http://example.com/media/example.jpg"], @@ -27,4 +23,30 @@ defmodule Pleroma.Web.MediaProxy.Invalidation.ScriptTest do               ) == {:error, "\"not found script path\""}      end)    end + +  describe "url formatting" do +    setup do +      urls = [ +        "https://bikeshed.party/media/foo.png", +        "http://safe.millennial.space/proxy/wheeeee.gif", +        "https://lain.com/proxy/mediafile.mp4?foo&bar=true", +        "http://localhost:4000/media/upload.jpeg" +      ] + +      [urls: urls] +    end + +    test "with invalid formatter", %{urls: urls} do +      assert urls == Invalidation.Script.maybe_format_urls(urls, nil) +    end + +    test "with :htcacheclean formatter", %{urls: urls} do +      assert [ +               "https://bikeshed.party:443/media/foo.png?", +               "http://safe.millennial.space:80/proxy/wheeeee.gif?", +               "https://lain.com:443/proxy/mediafile.mp4?foo&bar=true", +               "http://localhost:4000/media/upload.jpeg?" +             ] == Invalidation.Script.maybe_format_urls(urls, :htcacheclean) +    end +  end  end diff --git a/test/pleroma/web/media_proxy/invalidation_test.exs b/test/pleroma/web/media_proxy/invalidation_test.exs index aa1435ac0..c77b8c94a 100644 --- a/test/pleroma/web/media_proxy/invalidation_test.exs +++ b/test/pleroma/web/media_proxy/invalidation_test.exs @@ -1,12 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MediaProxy.InvalidationTest do -  use ExUnit.Case -  use Pleroma.Tests.Helpers +  use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.Web.MediaProxy.Invalidation    import ExUnit.CaptureLog @@ -15,17 +13,13 @@ defmodule Pleroma.Web.MediaProxy.InvalidationTest do    setup do: clear_config([:media_proxy]) -  setup do -    on_exit(fn -> Cachex.clear(:banned_urls_cache) end) -  end -    describe "Invalidation.Http" do      test "perform request to clear cache" do -      Config.put([:media_proxy, :enabled], false) -      Config.put([:media_proxy, :invalidation, :enabled], true) -      Config.put([:media_proxy, :invalidation, :provider], Invalidation.Http) +      clear_config([:media_proxy, :enabled], false) +      clear_config([:media_proxy, :invalidation, :enabled], true) +      clear_config([:media_proxy, :invalidation, :provider], Invalidation.Http) -      Config.put([Invalidation.Http], method: :purge, headers: [{"x-refresh", 1}]) +      clear_config([Invalidation.Http], method: :purge, headers: [{"x-refresh", 1}])        image_url = "http://example.com/media/example.jpg"        Pleroma.Web.MediaProxy.put_in_banned_urls(image_url) @@ -48,10 +42,10 @@ defmodule Pleroma.Web.MediaProxy.InvalidationTest do    describe "Invalidation.Script" do      test "run script to clear cache" do -      Config.put([:media_proxy, :enabled], false) -      Config.put([:media_proxy, :invalidation, :enabled], true) -      Config.put([:media_proxy, :invalidation, :provider], Invalidation.Script) -      Config.put([Invalidation.Script], script_path: "purge-nginx") +      clear_config([:media_proxy, :enabled], false) +      clear_config([:media_proxy, :invalidation, :enabled], true) +      clear_config([:media_proxy, :invalidation, :provider], Invalidation.Script) +      clear_config([Invalidation.Script], script_path: "purge-nginx")        image_url = "http://example.com/media/example.jpg"        Pleroma.Web.MediaProxy.put_in_banned_urls(image_url) diff --git a/test/pleroma/web/media_proxy/media_proxy_controller_test.exs b/test/pleroma/web/media_proxy/media_proxy_controller_test.exs index e9b584822..2a449e56d 100644 --- a/test/pleroma/web/media_proxy/media_proxy_controller_test.exs +++ b/test/pleroma/web/media_proxy/media_proxy_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MediaProxy.MediaProxyControllerTest do @@ -10,10 +10,6 @@ defmodule Pleroma.Web.MediaProxy.MediaProxyControllerTest do    alias Pleroma.Web.MediaProxy    alias Plug.Conn -  setup do -    on_exit(fn -> Cachex.clear(:banned_urls_cache) end) -  end -    describe "Media Proxy" do      setup do        clear_config([:media_proxy, :enabled], true) @@ -37,7 +33,7 @@ defmodule Pleroma.Web.MediaProxy.MediaProxyControllerTest do      end      test "it returns 403 for invalid signature", %{conn: conn, url: url} do -      Pleroma.Config.put([Pleroma.Web.Endpoint, :secret_key_base], "000") +      clear_config([Pleroma.Web.Endpoint, :secret_key_base], "000")        %{path: path} = URI.parse(url)        assert %Conn{ @@ -132,7 +128,7 @@ defmodule Pleroma.Web.MediaProxy.MediaProxyControllerTest do      end      test "it returns 403 for invalid signature", %{conn: conn, url: url} do -      Pleroma.Config.put([Pleroma.Web.Endpoint, :secret_key_base], "000") +      clear_config([Pleroma.Web.Endpoint, :secret_key_base], "000")        %{path: path} = URI.parse(url)        assert %Conn{ diff --git a/test/pleroma/web/media_proxy_test.exs b/test/pleroma/web/media_proxy_test.exs index 0e6df826c..b5ee6328d 100644 --- a/test/pleroma/web/media_proxy_test.exs +++ b/test/pleroma/web/media_proxy_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MediaProxyTest do @@ -11,8 +11,7 @@ defmodule Pleroma.Web.MediaProxyTest do    alias Pleroma.Web.MediaProxy    defp decode_result(encoded) do -    [_, "proxy", sig, base64 | _] = URI.parse(encoded).path |> String.split("/") -    {:ok, decoded} = MediaProxy.decode_url(sig, base64) +    {:ok, decoded} = MediaProxy.decode_url(encoded)      decoded    end diff --git a/test/pleroma/web/metadata/player_view_test.exs b/test/pleroma/web/metadata/player_view_test.exs index e6c990242..58caf6efd 100644 --- a/test/pleroma/web/metadata/player_view_test.exs +++ b/test/pleroma/web/metadata/player_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Metadata.PlayerViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.Metadata.PlayerView diff --git a/test/pleroma/web/metadata/providers/feed_test.exs b/test/pleroma/web/metadata/providers/feed_test.exs index e6e5cc5ed..013d42498 100644 --- a/test/pleroma/web/metadata/providers/feed_test.exs +++ b/test/pleroma/web/metadata/providers/feed_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Metadata.Providers.FeedTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.Metadata.Providers.Feed diff --git a/test/pleroma/web/metadata/providers/open_graph_test.exs b/test/pleroma/web/metadata/providers/open_graph_test.exs index 218540e6c..fc44b3cbd 100644 --- a/test/pleroma/web/metadata/providers/open_graph_test.exs +++ b/test/pleroma/web/metadata/providers/open_graph_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Metadata.Providers.OpenGraphTest do @@ -66,7 +66,7 @@ defmodule Pleroma.Web.Metadata.Providers.OpenGraphTest do    end    test "it does not render attachments if post is nsfw" do -    Pleroma.Config.put([Pleroma.Web.Metadata, :unfurl_nsfw], false) +    clear_config([Pleroma.Web.Metadata, :unfurl_nsfw], false)      user = insert(:user, avatar: %{"url" => [%{"href" => "https://pleroma.gov/tenshi.png"}]})      note = diff --git a/test/pleroma/web/metadata/providers/rel_me_test.exs b/test/pleroma/web/metadata/providers/rel_me_test.exs index 2293d6e13..0db6e7d22 100644 --- a/test/pleroma/web/metadata/providers/rel_me_test.exs +++ b/test/pleroma/web/metadata/providers/rel_me_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Metadata.Providers.RelMeTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.Metadata.Providers.RelMe diff --git a/test/pleroma/web/metadata/providers/restrict_indexing_test.exs b/test/pleroma/web/metadata/providers/restrict_indexing_test.exs index 52399fdc8..aa253e5e2 100644 --- a/test/pleroma/web/metadata/providers/restrict_indexing_test.exs +++ b/test/pleroma/web/metadata/providers/restrict_indexing_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Metadata.Providers.RestrictIndexingTest do diff --git a/test/pleroma/web/metadata/providers/twitter_card_test.exs b/test/pleroma/web/metadata/providers/twitter_card_test.exs index 10931b5ba..a35e44356 100644 --- a/test/pleroma/web/metadata/providers/twitter_card_test.exs +++ b/test/pleroma/web/metadata/providers/twitter_card_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do @@ -54,7 +54,7 @@ defmodule Pleroma.Web.Metadata.Providers.TwitterCardTest do    end    test "it renders avatar not attachment if post is nsfw and unfurl_nsfw is disabled" do -    Pleroma.Config.put([Pleroma.Web.Metadata, :unfurl_nsfw], false) +    clear_config([Pleroma.Web.Metadata, :unfurl_nsfw], false)      user = insert(:user, name: "Jimmy Hendriks", bio: "born 19 March 1994")      {:ok, activity} = CommonAPI.post(user, %{status: "HI"}) diff --git a/test/pleroma/web/metadata/utils_test.exs b/test/pleroma/web/metadata/utils_test.exs index 8183256d8..074bd2e2f 100644 --- a/test/pleroma/web/metadata/utils_test.exs +++ b/test/pleroma/web/metadata/utils_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Metadata.UtilsTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.Metadata.Utils diff --git a/test/pleroma/web/mongoose_im_controller_test.exs b/test/pleroma/web/mongoose_im_controller_test.exs index e3a8aa3d8..43c4dfa33 100644 --- a/test/pleroma/web/mongoose_im_controller_test.exs +++ b/test/pleroma/web/mongoose_im_controller_test.exs @@ -1,15 +1,15 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.MongooseIMControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory    test "/user_exists", %{conn: conn} do      _user = insert(:user, nickname: "lain")      _remote_user = insert(:user, nickname: "alice", local: false) -    _deactivated_user = insert(:user, nickname: "konata", deactivated: true) +    _deactivated_user = insert(:user, nickname: "konata", is_active: false)      res =        conn @@ -41,13 +41,13 @@ defmodule Pleroma.Web.MongooseIMControllerTest do    end    test "/check_password", %{conn: conn} do -    user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("cool")) +    user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("cool"))      _deactivated_user =        insert(:user,          nickname: "konata", -        deactivated: true, -        password_hash: Pbkdf2.hash_pwd_salt("cool") +        is_active: false, +        password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("cool")        )      res = diff --git a/test/pleroma/web/node_info_test.exs b/test/pleroma/web/node_info_test.exs index 06b33607f..ee6fdaae8 100644 --- a/test/pleroma/web/node_info_test.exs +++ b/test/pleroma/web/node_info_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.NodeInfoTest do @@ -7,8 +7,6 @@ defmodule Pleroma.Web.NodeInfoTest do    import Pleroma.Factory -  alias Pleroma.Config -    setup do: clear_config([:mrf_simple])    setup do: clear_config(:instance) @@ -93,7 +91,7 @@ defmodule Pleroma.Web.NodeInfoTest do      assert "safe_dm_mentions" in response["metadata"]["features"] -    Config.put([:instance, :safe_dm_mentions], false) +    clear_config([:instance, :safe_dm_mentions], false)      response =        conn @@ -107,7 +105,7 @@ defmodule Pleroma.Web.NodeInfoTest do      setup do: clear_config([:instance, :federating])      test "it shows if federation is enabled/disabled", %{conn: conn} do -      Config.put([:instance, :federating], true) +      clear_config([:instance, :federating], true)        response =          conn @@ -116,7 +114,7 @@ defmodule Pleroma.Web.NodeInfoTest do        assert response["metadata"]["federation"]["enabled"] == true -      Config.put([:instance, :federating], false) +      clear_config([:instance, :federating], false)        response =          conn diff --git a/test/pleroma/web/o_auth/app_test.exs b/test/pleroma/web/o_auth/app_test.exs index 993a490e0..fc2f0d940 100644 --- a/test/pleroma/web/o_auth/app_test.exs +++ b/test/pleroma/web/o_auth/app_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OAuth.AppTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.OAuth.App    import Pleroma.Factory diff --git a/test/pleroma/web/o_auth/authorization_test.exs b/test/pleroma/web/o_auth/authorization_test.exs index d74b26cf8..fc1c04c4c 100644 --- a/test/pleroma/web/o_auth/authorization_test.exs +++ b/test/pleroma/web/o_auth/authorization_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OAuth.AuthorizationTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.OAuth.App    alias Pleroma.Web.OAuth.Authorization    import Pleroma.Factory diff --git a/test/pleroma/web/o_auth/ldap_authorization_test.exs b/test/pleroma/web/o_auth/ldap_authorization_test.exs index 63b1c0eb8..61b9ce6b7 100644 --- a/test/pleroma/web/o_auth/ldap_authorization_test.exs +++ b/test/pleroma/web/o_auth/ldap_authorization_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OAuth.LDAPAuthorizationTest do @@ -18,7 +18,7 @@ defmodule Pleroma.Web.OAuth.LDAPAuthorizationTest do    @tag @skip    test "authorizes the existing user using LDAP credentials" do      password = "testpassword" -    user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password)) +    user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))      app = insert(:oauth_app, scopes: ["read", "write"])      host = Pleroma.Config.get([:ldap, :host]) |> to_charlist @@ -101,7 +101,7 @@ defmodule Pleroma.Web.OAuth.LDAPAuthorizationTest do    @tag @skip    test "disallow authorization for wrong LDAP credentials" do      password = "testpassword" -    user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password)) +    user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))      app = insert(:oauth_app, scopes: ["read", "write"])      host = Pleroma.Config.get([:ldap, :host]) |> to_charlist diff --git a/test/pleroma/web/o_auth/mfa_controller_test.exs b/test/pleroma/web/o_auth/mfa_controller_test.exs index 6ecd0f6c9..17bbde85b 100644 --- a/test/pleroma/web/o_auth/mfa_controller_test.exs +++ b/test/pleroma/web/o_auth/mfa_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OAuth.MFAControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory    alias Pleroma.MFA @@ -20,7 +20,7 @@ defmodule Pleroma.Web.OAuth.MFAControllerTest do        insert(:user,          multi_factor_authentication_settings: %MFA.Settings{            enabled: true, -          backup_codes: [Pbkdf2.hash_pwd_salt("test-code")], +          backup_codes: [Pleroma.Password.Pbkdf2.hash_pwd_salt("test-code")],            totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true}          }        ) @@ -246,7 +246,7 @@ defmodule Pleroma.Web.OAuth.MFAControllerTest do        hashed_codes =          backup_codes -        |> Enum.map(&Pbkdf2.hash_pwd_salt(&1)) +        |> Enum.map(&Pleroma.Password.Pbkdf2.hash_pwd_salt(&1))        user =          insert(:user, diff --git a/test/pleroma/web/o_auth/o_auth_controller_test.exs b/test/pleroma/web/o_auth/o_auth_controller_test.exs index ac22856ea..0fdd5b8e9 100644 --- a/test/pleroma/web/o_auth/o_auth_controller_test.exs +++ b/test/pleroma/web/o_auth/o_auth_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OAuth.OAuthControllerTest do @@ -316,7 +316,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do             app: app,             conn: conn           } do -      user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("testpassword")) +      user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("testpassword"))        registration = insert(:registration, user: nil)        redirect_uri = OAuthController.default_redirect_uri(app) @@ -347,7 +347,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do             app: app,             conn: conn           } do -      user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt("testpassword")) +      user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("testpassword"))        registration = insert(:registration, user: nil)        unlisted_redirect_uri = "http://cross-site-request.com" @@ -790,7 +790,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do      test "issues a token for `password` grant_type with valid credentials, with full permissions by default" do        password = "testpassword" -      user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password)) +      user = insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password))        app = insert(:oauth_app, scopes: ["read", "write"]) @@ -805,10 +805,12 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do            "client_secret" => app.client_secret          }) -      assert %{"access_token" => token} = json_response(conn, 200) +      assert %{"id" => id, "access_token" => access_token} = json_response(conn, 200) -      token = Repo.get_by(Token, token: token) +      token = Repo.get_by(Token, token: access_token)        assert token +      assert token.id == id +      assert token.token == access_token        assert token.scopes == app.scopes      end @@ -818,7 +820,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do        user =          insert(:user, -          password_hash: Pbkdf2.hash_pwd_salt(password), +          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),            multi_factor_authentication_settings: %MFA.Settings{              enabled: true,              totp: %MFA.Settings.TOTP{secret: otp_secret, confirmed: true} @@ -923,12 +925,12 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do      end      test "rejects token exchange for valid credentials belonging to unconfirmed user and confirmation is required" do -      Pleroma.Config.put([:instance, :account_activation_required], true) +      clear_config([:instance, :account_activation_required], true)        password = "testpassword"        {:ok, user} = -        insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password)) -        |> User.confirmation_changeset(need_confirmation: true) +        insert(:user, password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password)) +        |> User.confirmation_changeset(set_confirmation: false)          |> User.update_and_set_cache()        refute Pleroma.User.account_status(user) == :active @@ -955,8 +957,8 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do        user =          insert(:user, -          password_hash: Pbkdf2.hash_pwd_salt(password), -          deactivated: true +          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password), +          is_active: false          )        app = insert(:oauth_app) @@ -983,7 +985,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do        user =          insert(:user, -          password_hash: Pbkdf2.hash_pwd_salt(password), +          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password),            password_reset_pending: true          ) @@ -1007,13 +1009,13 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do      end      test "rejects token exchange for user with confirmation_pending set to true" do -      Pleroma.Config.put([:instance, :account_activation_required], true) +      clear_config([:instance, :account_activation_required], true)        password = "testpassword"        user =          insert(:user, -          password_hash: Pbkdf2.hash_pwd_salt(password), -          confirmation_pending: true +          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password), +          is_confirmed: false          )        app = insert(:oauth_app, scopes: ["read", "write"]) @@ -1038,7 +1040,11 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do      test "rejects token exchange for valid credentials belonging to an unapproved user" do        password = "testpassword" -      user = insert(:user, password_hash: Pbkdf2.hash_pwd_salt(password), approval_pending: true) +      user = +        insert(:user, +          password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt(password), +          is_approved: false +        )        refute Pleroma.User.account_status(user) == :active @@ -1082,7 +1088,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do      setup do: clear_config([:oauth2, :issue_new_refresh_token])      test "issues a new access token with keep fresh token" do -      Pleroma.Config.put([:oauth2, :issue_new_refresh_token], true) +      clear_config([:oauth2, :issue_new_refresh_token], true)        user = insert(:user)        app = insert(:oauth_app, scopes: ["read", "write"]) @@ -1121,7 +1127,7 @@ defmodule Pleroma.Web.OAuth.OAuthControllerTest do      end      test "issues a new access token with new fresh token" do -      Pleroma.Config.put([:oauth2, :issue_new_refresh_token], false) +      clear_config([:oauth2, :issue_new_refresh_token], false)        user = insert(:user)        app = insert(:oauth_app, scopes: ["read", "write"]) diff --git a/test/pleroma/web/o_auth/token/utils_test.exs b/test/pleroma/web/o_auth/token/utils_test.exs index a610d92f8..d2e7a0904 100644 --- a/test/pleroma/web/o_auth/token/utils_test.exs +++ b/test/pleroma/web/o_auth/token/utils_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OAuth.Token.UtilsTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.OAuth.Token.Utils    import Pleroma.Factory diff --git a/test/pleroma/web/o_auth/token_test.exs b/test/pleroma/web/o_auth/token_test.exs index c88b9cc98..8c0858ebc 100644 --- a/test/pleroma/web/o_auth/token_test.exs +++ b/test/pleroma/web/o_auth/token_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OAuth.TokenTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Repo    alias Pleroma.Web.OAuth.App    alias Pleroma.Web.OAuth.Authorization diff --git a/test/pleroma/web/o_status/o_status_controller_test.exs b/test/pleroma/web/o_status/o_status_controller_test.exs index 65b2c22db..2038f4ddd 100644 --- a/test/pleroma/web/o_status/o_status_controller_test.exs +++ b/test/pleroma/web/o_status/o_status_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.OStatus.OStatusControllerTest do @@ -72,7 +72,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do      test "redirects to /notice/id for html format", %{conn: conn} do        note_activity = insert(:note_activity) -      object = Object.normalize(note_activity) +      object = Object.normalize(note_activity, fetch: false)        [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, object.data["id"]))        url = "/objects/#{uuid}" @@ -82,7 +82,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do      test "404s on private objects", %{conn: conn} do        note_activity = insert(:direct_note_activity) -      object = Object.normalize(note_activity) +      object = Object.normalize(note_activity, fetch: false)        [_, uuid] = hd(Regex.scan(~r/.+\/([\w-]+)$/, object.data["id"]))        conn @@ -133,7 +133,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        conn: conn      } do        note_activity = insert(:note_activity) -      expected_redirect_url = Object.normalize(note_activity).data["id"] +      expected_redirect_url = Object.normalize(note_activity, fetch: false).data["id"]        redirect_url =          conn @@ -144,13 +144,19 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do        assert redirect_url == expected_redirect_url      end -    test "returns a 404 on remote notice when json requested", %{conn: conn} do +    test "redirects to a proper object URL when json requested and the object is remote", %{ +      conn: conn +    } do        note_activity = insert(:note_activity, local: false) +      expected_redirect_url = Object.normalize(note_activity, fetch: false).data["id"] -      conn -      |> put_req_header("accept", "application/activity+json") -      |> get("/notice/#{note_activity.id}") -      |> response(404) +      redirect_url = +        conn +        |> put_req_header("accept", "application/activity+json") +        |> get("/notice/#{note_activity.id}") +        |> redirected_to() + +      assert redirect_url == expected_redirect_url      end      test "500s when actor not found", %{conn: conn} do @@ -230,7 +236,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do    describe "GET /notice/:id/embed_player" do      setup do        note_activity = insert(:note_activity) -      object = Pleroma.Object.normalize(note_activity) +      object = Pleroma.Object.normalize(note_activity, fetch: false)        object_data =          Map.put(object.data, "attachment", [ @@ -287,7 +293,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do      test "404s when attachment is empty", %{conn: conn} do        note_activity = insert(:note_activity) -      object = Pleroma.Object.normalize(note_activity) +      object = Pleroma.Object.normalize(note_activity, fetch: false)        object_data = Map.put(object.data, "attachment", [])        object @@ -301,7 +307,7 @@ defmodule Pleroma.Web.OStatus.OStatusControllerTest do      test "404s when attachment isn't audio or video", %{conn: conn} do        note_activity = insert(:note_activity) -      object = Pleroma.Object.normalize(note_activity) +      object = Pleroma.Object.normalize(note_activity, fetch: false)        object_data =          Map.put(object.data, "attachment", [ diff --git a/test/pleroma/web/pleroma_api/controllers/account_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/account_controller_test.exs index 07909d48b..9f14c5577 100644 --- a/test/pleroma/web/pleroma_api/controllers/account_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/account_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do @@ -17,10 +17,10 @@ defmodule Pleroma.Web.PleromaAPI.AccountControllerTest do      setup do        {:ok, user} =          insert(:user) -        |> User.confirmation_changeset(need_confirmation: true) +        |> User.confirmation_changeset(set_confirmation: false)          |> User.update_and_set_cache() -      assert user.confirmation_pending +      refute user.is_confirmed        [user: user]      end diff --git a/test/pleroma/web/pleroma_api/controllers/backup_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/backup_controller_test.exs index f1941f6dd..3ee660a05 100644 --- a/test/pleroma/web/pleroma_api/controllers/backup_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/backup_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.BackupControllerTest do diff --git a/test/pleroma/web/pleroma_api/controllers/chat_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/chat_controller_test.exs index a6c9d0c1b..99b0d43a7 100644 --- a/test/pleroma/web/pleroma_api/controllers/chat_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/chat_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do    use Pleroma.Web.ConnCase @@ -22,7 +22,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do        {:ok, create} = CommonAPI.post_chat_message(other_user, user, "sup")        {:ok, _create} = CommonAPI.post_chat_message(other_user, user, "sup part 2")        {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id) -      object = Object.normalize(create, false) +      object = Object.normalize(create, fetch: false)        cm_ref = MessageReference.for_chat_and_object(chat, object)        assert cm_ref.unread == true @@ -52,7 +52,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do        {:ok, create} = CommonAPI.post_chat_message(other_user, user, "sup")        {:ok, _create} = CommonAPI.post_chat_message(other_user, user, "sup part 2")        {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id) -      object = Object.normalize(create, false) +      object = Object.normalize(create, fetch: false)        cm_ref = MessageReference.for_chat_and_object(chat, object)        assert cm_ref.unread == true @@ -158,7 +158,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do        {:ok, other_message} = CommonAPI.post_chat_message(recipient, user, "nico nico ni") -      object = Object.normalize(message, false) +      object = Object.normalize(message, fetch: false)        chat = Chat.get(user.id, recipient.ap_id) @@ -176,7 +176,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do        assert %{data: %{"type" => "Tombstone"}} = Object.get_by_id(object.id)        # Deleting other people's messages just removes the reference -      object = Object.normalize(other_message, false) +      object = Object.normalize(other_message, fetch: false)        cm_ref = MessageReference.for_chat_and_object(chat, object)        result = @@ -211,12 +211,12 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do        assert String.match?(                 next, -               ~r(#{api_endpoint}.*/messages\?id=.*&limit=\d+&max_id=.*; rel=\"next\"$) +               ~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*; rel=\"next\"$)               )        assert String.match?(                 prev, -               ~r(#{api_endpoint}.*/messages\?id=.*&limit=\d+&min_id=.*; rel=\"prev\"$) +               ~r(#{api_endpoint}.*/messages\?limit=\d+&min_id=.*; rel=\"prev\"$)               )        assert length(result) == 20 @@ -229,12 +229,12 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do        assert String.match?(                 next, -               ~r(#{api_endpoint}.*/messages\?id=.*&limit=\d+&max_id=.*; rel=\"next\"$) +               ~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*; rel=\"next\"$)               )        assert String.match?(                 prev, -               ~r(#{api_endpoint}.*/messages\?id=.*&limit=\d+&max_id=.*&min_id=.*; rel=\"prev\"$) +               ~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*&min_id=.*; rel=\"prev\"$)               )        assert length(result) == 10 @@ -304,139 +304,165 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do      end    end -  describe "GET /api/v1/pleroma/chats" do -    setup do: oauth_access(["read:chats"]) - -    test "it does not return chats with deleted users", %{conn: conn, user: user} do -      recipient = insert(:user) -      {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) - -      Pleroma.Repo.delete(recipient) -      User.invalidate_cache(recipient) - -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) - -      assert length(result) == 0 -    end - -    test "it does not return chats with users you blocked", %{conn: conn, user: user} do -      recipient = insert(:user) - -      {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) - -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) - -      assert length(result) == 1 - -      User.block(user, recipient) - -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) - -      assert length(result) == 0 -    end - -    test "it does not return chats with users you muted", %{conn: conn, user: user} do -      recipient = insert(:user) - -      {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) - -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) - -      assert length(result) == 1 +  for tested_endpoint <- ["/api/v1/pleroma/chats", "/api/v2/pleroma/chats"] do +    describe "GET #{tested_endpoint}" do +      setup do: oauth_access(["read:chats"]) -      User.mute(user, recipient) - -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) - -      assert length(result) == 0 - -      result = -        conn -        |> get("/api/v1/pleroma/chats?with_muted=true") -        |> json_response_and_validate_schema(200) - -      assert length(result) == 1 -    end - -    test "it returns all chats", %{conn: conn, user: user} do -      Enum.each(1..30, fn _ -> +      test "it does not return chats with deleted users", %{conn: conn, user: user} do          recipient = insert(:user)          {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) -      end) -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) +        Pleroma.Repo.delete(recipient) +        User.invalidate_cache(recipient) -      assert length(result) == 30 -    end +        result = +          conn +          |> get(unquote(tested_endpoint)) +          |> json_response_and_validate_schema(200) -    test "it return a list of chats the current user is participating in, in descending order of updates", -         %{conn: conn, user: user} do -      har = insert(:user) -      jafnhar = insert(:user) -      tridi = insert(:user) +        assert length(result) == 0 +      end -      {:ok, chat_1} = Chat.get_or_create(user.id, har.ap_id) -      :timer.sleep(1000) -      {:ok, _chat_2} = Chat.get_or_create(user.id, jafnhar.ap_id) -      :timer.sleep(1000) -      {:ok, chat_3} = Chat.get_or_create(user.id, tridi.ap_id) -      :timer.sleep(1000) +      test "it does not return chats with users you blocked", %{conn: conn, user: user} do +        recipient = insert(:user) -      # bump the second one -      {:ok, chat_2} = Chat.bump_or_create(user.id, jafnhar.ap_id) +        {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) +        result = +          conn +          |> get(unquote(tested_endpoint)) +          |> json_response_and_validate_schema(200) -      ids = Enum.map(result, & &1["id"]) +        assert length(result) == 1 -      assert ids == [ -               chat_2.id |> to_string(), -               chat_3.id |> to_string(), -               chat_1.id |> to_string() -             ] -    end +        User.block(user, recipient) -    test "it is not affected by :restrict_unauthenticated setting (issue #1973)", %{ -      conn: conn, -      user: user -    } do -      clear_config([:restrict_unauthenticated, :profiles, :local], true) -      clear_config([:restrict_unauthenticated, :profiles, :remote], true) +        result = +          conn +          |> get(unquote(tested_endpoint)) +          |> json_response_and_validate_schema(200) -      user2 = insert(:user) -      user3 = insert(:user, local: false) +        assert length(result) == 0 +      end -      {:ok, _chat_12} = Chat.get_or_create(user.id, user2.ap_id) -      {:ok, _chat_13} = Chat.get_or_create(user.id, user3.ap_id) +      test "it does not return chats with users you muted", %{conn: conn, user: user} do +        recipient = insert(:user) -      result = -        conn -        |> get("/api/v1/pleroma/chats") -        |> json_response_and_validate_schema(200) +        {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) -      account_ids = Enum.map(result, &get_in(&1, ["account", "id"])) -      assert Enum.sort(account_ids) == Enum.sort([user2.id, user3.id]) +        result = +          conn +          |> get(unquote(tested_endpoint)) +          |> json_response_and_validate_schema(200) + +        assert length(result) == 1 + +        User.mute(user, recipient) + +        result = +          conn +          |> get(unquote(tested_endpoint)) +          |> json_response_and_validate_schema(200) + +        assert length(result) == 0 + +        result = +          conn +          |> get("#{unquote(tested_endpoint)}?with_muted=true") +          |> json_response_and_validate_schema(200) + +        assert length(result) == 1 +      end + +      if tested_endpoint == "/api/v1/pleroma/chats" do +        test "it returns all chats", %{conn: conn, user: user} do +          Enum.each(1..30, fn _ -> +            recipient = insert(:user) +            {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) +          end) + +          result = +            conn +            |> get(unquote(tested_endpoint)) +            |> json_response_and_validate_schema(200) + +          assert length(result) == 30 +        end +      else +        test "it paginates chats", %{conn: conn, user: user} do +          Enum.each(1..30, fn _ -> +            recipient = insert(:user) +            {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id) +          end) + +          result = +            conn +            |> get(unquote(tested_endpoint)) +            |> json_response_and_validate_schema(200) + +          assert length(result) == 20 +          last_id = List.last(result)["id"] + +          result = +            conn +            |> get(unquote(tested_endpoint) <> "?max_id=#{last_id}") +            |> json_response_and_validate_schema(200) + +          assert length(result) == 10 +        end +      end + +      test "it return a list of chats the current user is participating in, in descending order of updates", +           %{conn: conn, user: user} do +        har = insert(:user) +        jafnhar = insert(:user) +        tridi = insert(:user) + +        {:ok, chat_1} = Chat.get_or_create(user.id, har.ap_id) +        {:ok, chat_1} = time_travel(chat_1, -3) +        {:ok, chat_2} = Chat.get_or_create(user.id, jafnhar.ap_id) +        {:ok, _chat_2} = time_travel(chat_2, -2) +        {:ok, chat_3} = Chat.get_or_create(user.id, tridi.ap_id) +        {:ok, chat_3} = time_travel(chat_3, -1) + +        # bump the second one +        {:ok, chat_2} = Chat.bump_or_create(user.id, jafnhar.ap_id) + +        result = +          conn +          |> get(unquote(tested_endpoint)) +          |> json_response_and_validate_schema(200) + +        ids = Enum.map(result, & &1["id"]) + +        assert ids == [ +                 chat_2.id |> to_string(), +                 chat_3.id |> to_string(), +                 chat_1.id |> to_string() +               ] +      end + +      test "it is not affected by :restrict_unauthenticated setting (issue #1973)", %{ +        conn: conn, +        user: user +      } do +        clear_config([:restrict_unauthenticated, :profiles, :local], true) +        clear_config([:restrict_unauthenticated, :profiles, :remote], true) + +        user2 = insert(:user) +        user3 = insert(:user, local: false) + +        {:ok, _chat_12} = Chat.get_or_create(user.id, user2.ap_id) +        {:ok, _chat_13} = Chat.get_or_create(user.id, user3.ap_id) + +        result = +          conn +          |> get(unquote(tested_endpoint)) +          |> json_response_and_validate_schema(200) + +        account_ids = Enum.map(result, &get_in(&1, ["account", "id"])) +        assert Enum.sort(account_ids) == Enum.sort([user2.id, user3.id]) +      end      end    end  end diff --git a/test/pleroma/web/pleroma_api/controllers/conversation_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/conversation_controller_test.exs index f2feeaaef..54f2c5a58 100644 --- a/test/pleroma/web/pleroma_api/controllers/conversation_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/conversation_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.ConversationControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Conversation.Participation    alias Pleroma.Repo @@ -104,7 +104,7 @@ defmodule Pleroma.Web.PleromaAPI.ConversationControllerTest do      [participation] = Participation.for_user(user)      participation = Repo.preload(participation, :recipients) -    assert user in participation.recipients +    assert refresh_record(user) in participation.recipients      assert other_user in participation.recipients    end diff --git a/test/pleroma/web/pleroma_api/controllers/emoji_file_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/emoji_file_controller_test.exs index 82de86ee3..547391249 100644 --- a/test/pleroma/web/pleroma_api/controllers/emoji_file_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/emoji_file_controller_test.exs @@ -1,10 +1,11 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.EmojiFileControllerTest do    use Pleroma.Web.ConnCase +  import Mock    import Tesla.Mock    import Pleroma.Factory @@ -12,8 +13,6 @@ defmodule Pleroma.Web.PleromaAPI.EmojiFileControllerTest do                  Pleroma.Config.get!([:instance, :static_dir]),                  "emoji"                ) -  setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false) -    setup do: clear_config([:instance, :public], true)    setup do @@ -200,6 +199,31 @@ defmodule Pleroma.Web.PleromaAPI.EmojiFileControllerTest do               }      end +    test "returns an error on add file when file system is not writable", %{ +      admin_conn: admin_conn +    } do +      pack_file = Path.join([@emoji_path, "not_loaded", "pack.json"]) + +      with_mocks([ +        {File, [:passthrough], [stat: fn ^pack_file -> {:error, :eacces} end]} +      ]) do +        assert admin_conn +               |> put_req_header("content-type", "multipart/form-data") +               |> post("/api/pleroma/emoji/packs/files?name=not_loaded", %{ +                 shortcode: "blank3", +                 filename: "dir/blank.png", +                 file: %Plug.Upload{ +                   filename: "blank.png", +                   path: "#{@emoji_path}/test_pack/blank.png" +                 } +               }) +               |> json_response_and_validate_schema(500) == %{ +                 "error" => +                   "Unexpected error occurred while adding file to pack. (POSIX error: Permission denied)" +               } +      end +    end +      test "remove file with not loaded pack", %{admin_conn: admin_conn} do        assert admin_conn               |> delete("/api/pleroma/emoji/packs/files?name=not_loaded&shortcode=blank3") diff --git a/test/pleroma/web/pleroma_api/controllers/emoji_pack_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/emoji_pack_controller_test.exs index 3445f0ca0..d1ba067b8 100644 --- a/test/pleroma/web/pleroma_api/controllers/emoji_pack_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/emoji_pack_controller_test.exs @@ -1,10 +1,11 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.EmojiPackControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: false +  import Mock    import Tesla.Mock    import Pleroma.Factory @@ -12,7 +13,6 @@ defmodule Pleroma.Web.PleromaAPI.EmojiPackControllerTest do                  Pleroma.Config.get!([:instance, :static_dir]),                  "emoji"                ) -  setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage], false)    setup do: clear_config([:instance, :public], true) @@ -30,7 +30,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiPackControllerTest do    end    test "GET /api/pleroma/emoji/packs when :public: false", %{conn: conn} do -    Config.put([:instance, :public], false) +    clear_config([:instance, :public], false)      conn |> get("/api/pleroma/emoji/packs") |> json_response_and_validate_schema(200)    end @@ -346,7 +346,7 @@ defmodule Pleroma.Web.PleromaAPI.EmojiPackControllerTest do      end    end -  describe "PATCH /api/pleroma/emoji/pack?name=:name" do +  describe "PATCH/update /api/pleroma/emoji/pack?name=:name" do      setup do        pack_file = "#{@emoji_path}/test_pack/pack.json"        original_content = File.read!(pack_file) @@ -365,6 +365,20 @@ defmodule Pleroma.Web.PleromaAPI.EmojiPackControllerTest do         }}      end +    test "returns error when file system not writable", %{admin_conn: conn} = ctx do +      with_mocks([ +        {File, [:passthrough], [stat: fn _ -> {:error, :eacces} end]} +      ]) do +        assert conn +               |> put_req_header("content-type", "multipart/form-data") +               |> patch( +                 "/api/pleroma/emoji/pack?name=test_pack", +                 %{"metadata" => ctx[:new_data]} +               ) +               |> json_response_and_validate_schema(500) +      end +    end +      test "for a pack without a fallback source", ctx do        assert ctx[:admin_conn]               |> put_req_header("content-type", "multipart/form-data") @@ -424,6 +438,46 @@ defmodule Pleroma.Web.PleromaAPI.EmojiPackControllerTest do    end    describe "POST/DELETE /api/pleroma/emoji/pack?name=:name" do +    test "returns an error on creates pack when file system not writable", %{ +      admin_conn: admin_conn +    } do +      path_pack = Path.join(@emoji_path, "test_pack") + +      with_mocks([ +        {File, [:passthrough], [mkdir: fn ^path_pack -> {:error, :eacces} end]} +      ]) do +        assert admin_conn +               |> post("/api/pleroma/emoji/pack?name=test_pack") +               |> json_response_and_validate_schema(500) == %{ +                 "error" => +                   "Unexpected error occurred while creating pack. (POSIX error: Permission denied)" +               } +      end +    end + +    test "returns an error on deletes pack when the file system is not writable", %{ +      admin_conn: admin_conn +    } do +      path_pack = Path.join(@emoji_path, "test_emoji_pack") + +      try do +        {:ok, _pack} = Pleroma.Emoji.Pack.create("test_emoji_pack") + +        with_mocks([ +          {File, [:passthrough], [rm_rf: fn ^path_pack -> {:error, :eacces, path_pack} end]} +        ]) do +          assert admin_conn +                 |> delete("/api/pleroma/emoji/pack?name=test_emoji_pack") +                 |> json_response_and_validate_schema(500) == %{ +                   "error" => +                     "Couldn't delete the `test_emoji_pack` pack (POSIX error: Permission denied)" +                 } +        end +      after +        File.rm_rf(path_pack) +      end +    end +      test "creating and deleting a pack", %{admin_conn: admin_conn} do        assert admin_conn               |> post("/api/pleroma/emoji/pack?name=test_created") diff --git a/test/pleroma/web/pleroma_api/controllers/emoji_reaction_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/emoji_reaction_controller_test.exs index bda9c20c6..28483985c 100644 --- a/test/pleroma/web/pleroma_api/controllers/emoji_reaction_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/emoji_reaction_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.EmojiReactionControllerTest do diff --git a/test/pleroma/web/pleroma_api/controllers/instances_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/instances_controller_test.exs index 13491ed9c..54cf9d083 100644 --- a/test/pleroma/web/pleroma_api/controllers/instances_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/instances_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaApi.InstancesControllerTest do diff --git a/test/pleroma/web/pleroma_api/controllers/mascot_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/mascot_controller_test.exs index 289119d45..0011ddd54 100644 --- a/test/pleroma/web/pleroma_api/controllers/mascot_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/mascot_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.MascotControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.User diff --git a/test/pleroma/web/pleroma_api/controllers/notification_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/notification_controller_test.exs index bb4fe6c49..08f374908 100644 --- a/test/pleroma/web/pleroma_api/controllers/notification_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/notification_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.NotificationControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Notification    alias Pleroma.Repo diff --git a/test/pleroma/web/pleroma_api/controllers/report_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/report_controller_test.exs new file mode 100644 index 000000000..c507aeca0 --- /dev/null +++ b/test/pleroma/web/pleroma_api/controllers/report_controller_test.exs @@ -0,0 +1,80 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.PleromaAPI.ReportControllerTest do +  use Pleroma.Web.ConnCase, async: true + +  import Pleroma.Factory + +  alias Pleroma.Web.CommonAPI + +  describe "GET /api/v0/pleroma/reports" do +    test "returns list of own reports" do +      %{conn: reporter_conn, user: reporter} = oauth_access(["read:reports"]) +      %{conn: reported_conn, user: reported} = oauth_access(["read:reports"]) +      activity = insert(:note_activity, user: reported) + +      {:ok, %{id: report_id}} = +        CommonAPI.report(reporter, %{ +          account_id: reported.id, +          comment: "You stole my sandwich!", +          status_ids: [activity.id] +        }) + +      assert reported_response = +               reported_conn +               |> get("/api/v0/pleroma/reports") +               |> json_response_and_validate_schema(:ok) + +      assert reported_response == %{"reports" => [], "total" => 0} + +      assert reporter_response = +               reporter_conn +               |> get("/api/v0/pleroma/reports") +               |> json_response_and_validate_schema(:ok) + +      assert %{"reports" => [report], "total" => 1} = reporter_response +      assert report["id"] == report_id +      refute report["notes"] +    end +  end + +  describe "GET /api/v0/pleroma/reports/:id" do +    test "returns report by its id" do +      %{conn: reporter_conn, user: reporter} = oauth_access(["read:reports"]) +      %{conn: reported_conn, user: reported} = oauth_access(["read:reports"]) +      activity = insert(:note_activity, user: reported) + +      {:ok, %{id: report_id}} = +        CommonAPI.report(reporter, %{ +          account_id: reported.id, +          comment: "You stole my sandwich!", +          status_ids: [activity.id] +        }) + +      assert reported_conn +             |> get("/api/v0/pleroma/reports/#{report_id}") +             |> json_response_and_validate_schema(:not_found) + +      assert response = +               reporter_conn +               |> get("/api/v0/pleroma/reports/#{report_id}") +               |> json_response_and_validate_schema(:ok) + +      assert response["id"] == report_id +      refute response["notes"] +    end + +    test "returns 404 when report id is invalid" do +      %{conn: conn, user: _user} = oauth_access(["read:reports"]) + +      assert response = +               conn +               |> get("/api/v0/pleroma/reports/0") +               |> json_response_and_validate_schema(:not_found) + +      assert response == %{"error" => "Record not found"} +    end +  end +end diff --git a/test/pleroma/web/pleroma_api/controllers/scrobble_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/scrobble_controller_test.exs index f39c07ac6..d4546f442 100644 --- a/test/pleroma/web/pleroma_api/controllers/scrobble_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/scrobble_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.ScrobbleControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Web.CommonAPI diff --git a/test/pleroma/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs index 22988c881..24074f4e5 100644 --- a/test/pleroma/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/two_factor_authentication_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.TwoFactorAuthenticationControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    import Pleroma.Factory    alias Pleroma.MFA.Settings diff --git a/test/pleroma/web/pleroma_api/controllers/user_import_controller_test.exs b/test/pleroma/web/pleroma_api/controllers/user_import_controller_test.exs index d83d33912..25a7f8374 100644 --- a/test/pleroma/web/pleroma_api/controllers/user_import_controller_test.exs +++ b/test/pleroma/web/pleroma_api/controllers/user_import_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.UserImportControllerTest do diff --git a/test/pleroma/web/pleroma_api/views/backup_view_test.exs b/test/pleroma/web/pleroma_api/views/backup_view_test.exs new file mode 100644 index 000000000..9b4298dd1 --- /dev/null +++ b/test/pleroma/web/pleroma_api/views/backup_view_test.exs @@ -0,0 +1,18 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.PleromaAPI.BackupViewTest do +  use Pleroma.DataCase, async: true +  alias Pleroma.User.Backup +  alias Pleroma.Web.PleromaAPI.BackupView +  import Pleroma.Factory + +  test "it renders the ID" do +    user = insert(:user) +    backup = Backup.new(user) + +    result = BackupView.render("show.json", backup: backup) +    assert result.id == backup.id +  end +end diff --git a/test/pleroma/web/pleroma_api/views/chat_message_reference_view_test.exs b/test/pleroma/web/pleroma_api/views/chat_message_reference_view_test.exs index 93eef00a2..6deaa2102 100644 --- a/test/pleroma/web/pleroma_api/views/chat_message_reference_view_test.exs +++ b/test/pleroma/web/pleroma_api/views/chat_message_reference_view_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.ChatMessageReferenceViewTest do @@ -31,7 +31,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatMessageReferenceViewTest do      chat = Chat.get(user.id, recipient.ap_id) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      cm_ref = MessageReference.for_chat_and_object(chat, object) @@ -58,7 +58,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatMessageReferenceViewTest do          media_id: upload.id        ) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      cm_ref = MessageReference.for_chat_and_object(chat, object) diff --git a/test/pleroma/web/pleroma_api/views/chat_view_test.exs b/test/pleroma/web/pleroma_api/views/chat_view_test.exs index 02484b705..5456c2de0 100644 --- a/test/pleroma/web/pleroma_api/views/chat_view_test.exs +++ b/test/pleroma/web/pleroma_api/views/chat_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.ChatViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Chat    alias Pleroma.Chat.MessageReference @@ -35,7 +35,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatViewTest do      {:ok, chat_message_creation} = CommonAPI.post_chat_message(user, recipient, "hello") -    chat_message = Object.normalize(chat_message_creation, false) +    chat_message = Object.normalize(chat_message_creation, fetch: false)      {:ok, chat} = Chat.get_or_create(user.id, recipient.ap_id) diff --git a/test/pleroma/web/pleroma_api/views/scrobble_view_test.exs b/test/pleroma/web/pleroma_api/views/scrobble_view_test.exs index 0f43cbdc3..382051f6f 100644 --- a/test/pleroma/web/pleroma_api/views/scrobble_view_test.exs +++ b/test/pleroma/web/pleroma_api/views/scrobble_view_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.PleromaAPI.ScrobbleViewTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.PleromaAPI.ScrobbleView diff --git a/test/pleroma/web/plugs/admin_secret_authentication_plug_test.exs b/test/pleroma/web/plugs/admin_secret_authentication_plug_test.exs index 23498badf..79561afb7 100644 --- a/test/pleroma/web/plugs/admin_secret_authentication_plug_test.exs +++ b/test/pleroma/web/plugs/admin_secret_authentication_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.AdminSecretAuthenticationPlugTest do @@ -35,7 +35,7 @@ defmodule Pleroma.Web.Plugs.AdminSecretAuthenticationPlugTest do      end      test "with `admin_token` query parameter", %{conn: conn} do -      Pleroma.Config.put(:admin_token, "password123") +      clear_config(:admin_token, "password123")        conn =          %{conn | params: %{"admin_token" => "wrong_password"}} @@ -54,7 +54,7 @@ defmodule Pleroma.Web.Plugs.AdminSecretAuthenticationPlugTest do      end      test "with `x-admin-token` HTTP header", %{conn: conn} do -      Pleroma.Config.put(:admin_token, "☕️") +      clear_config(:admin_token, "☕️")        conn =          conn diff --git a/test/pleroma/web/plugs/authentication_plug_test.exs b/test/pleroma/web/plugs/authentication_plug_test.exs index 3dedd38b2..118ab302a 100644 --- a/test/pleroma/web/plugs/authentication_plug_test.exs +++ b/test/pleroma/web/plugs/authentication_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.AuthenticationPlugTest do @@ -17,7 +17,7 @@ defmodule Pleroma.Web.Plugs.AuthenticationPlugTest do      user = %User{        id: 1,        name: "dude", -      password_hash: Pbkdf2.hash_pwd_salt("guy") +      password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("guy")      }      conn = diff --git a/test/pleroma/web/plugs/basic_auth_decoder_plug_test.exs b/test/pleroma/web/plugs/basic_auth_decoder_plug_test.exs index 2d6af228c..e90078eb5 100644 --- a/test/pleroma/web/plugs/basic_auth_decoder_plug_test.exs +++ b/test/pleroma/web/plugs/basic_auth_decoder_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.BasicAuthDecoderPlugTest do diff --git a/test/pleroma/web/plugs/cache_control_test.exs b/test/pleroma/web/plugs/cache_control_test.exs index fcf3d2be8..263961897 100644 --- a/test/pleroma/web/plugs/cache_control_test.exs +++ b/test/pleroma/web/plugs/cache_control_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.CacheControlTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Plug.Conn    test "Verify Cache-Control header on static assets", %{conn: conn} do diff --git a/test/pleroma/web/plugs/cache_test.exs b/test/pleroma/web/plugs/cache_test.exs index 93a66f5d3..0ceab6cab 100644 --- a/test/pleroma/web/plugs/cache_test.exs +++ b/test/pleroma/web/plugs/cache_test.exs @@ -1,9 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.CacheTest do -  use ExUnit.Case, async: true +  # Relies on Cachex, has to stay synchronous +  use Pleroma.DataCase    use Plug.Test    alias Pleroma.Web.Plugs.Cache @@ -24,11 +25,6 @@ defmodule Pleroma.Web.Plugs.CacheTest do    @ttl 5 -  setup do -    Cachex.clear(:web_resp_cache) -    :ok -  end -    test "caches a response" do      assert @miss_resp ==               conn(:get, "/") diff --git a/test/pleroma/web/plugs/ensure_authenticated_plug_test.exs b/test/pleroma/web/plugs/ensure_authenticated_plug_test.exs index 92ff19282..6b3ee3d87 100644 --- a/test/pleroma/web/plugs/ensure_authenticated_plug_test.exs +++ b/test/pleroma/web/plugs/ensure_authenticated_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.EnsureAuthenticatedPlugTest do diff --git a/test/pleroma/web/plugs/ensure_public_or_authenticated_plug_test.exs b/test/pleroma/web/plugs/ensure_public_or_authenticated_plug_test.exs index 211443a55..75c3b5784 100644 --- a/test/pleroma/web/plugs/ensure_public_or_authenticated_plug_test.exs +++ b/test/pleroma/web/plugs/ensure_public_or_authenticated_plug_test.exs @@ -1,18 +1,17 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlugTest do -  use Pleroma.Web.ConnCase, async: true +  use Pleroma.Web.ConnCase -  alias Pleroma.Config    alias Pleroma.User    alias Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlug    setup do: clear_config([:instance, :public])    test "it halts if not public and no user is assigned", %{conn: conn} do -    Config.put([:instance, :public], false) +    clear_config([:instance, :public], false)      conn =        conn @@ -23,7 +22,7 @@ defmodule Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlugTest do    end    test "it continues if public", %{conn: conn} do -    Config.put([:instance, :public], true) +    clear_config([:instance, :public], true)      ret_conn =        conn @@ -33,7 +32,7 @@ defmodule Pleroma.Web.Plugs.EnsurePublicOrAuthenticatedPlugTest do    end    test "it continues if a user is assigned, even if not public", %{conn: conn} do -    Config.put([:instance, :public], false) +    clear_config([:instance, :public], false)      conn =        conn diff --git a/test/pleroma/web/plugs/ensure_user_token_assigns_plug_test.exs b/test/pleroma/web/plugs/ensure_user_token_assigns_plug_test.exs index 9592820c7..28ec67158 100644 --- a/test/pleroma/web/plugs/ensure_user_token_assigns_plug_test.exs +++ b/test/pleroma/web/plugs/ensure_user_token_assigns_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.EnsureUserTokenAssignsPlugTest do diff --git a/test/pleroma/web/plugs/federating_plug_test.exs b/test/pleroma/web/plugs/federating_plug_test.exs index a4652f6c5..01ecd2a1e 100644 --- a/test/pleroma/web/plugs/federating_plug_test.exs +++ b/test/pleroma/web/plugs/federating_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.FederatingPlugTest do @@ -8,7 +8,7 @@ defmodule Pleroma.Web.Plugs.FederatingPlugTest do    setup do: clear_config([:instance, :federating])    test "returns and halt the conn when federating is disabled" do -    Pleroma.Config.put([:instance, :federating], false) +    clear_config([:instance, :federating], false)      conn =        build_conn() @@ -19,7 +19,7 @@ defmodule Pleroma.Web.Plugs.FederatingPlugTest do    end    test "does nothing when federating is enabled" do -    Pleroma.Config.put([:instance, :federating], true) +    clear_config([:instance, :federating], true)      conn =        build_conn() diff --git a/test/pleroma/web/plugs/frontend_static_plug_test.exs b/test/pleroma/web/plugs/frontend_static_plug_test.exs index 8b7b022fc..100b83d6a 100644 --- a/test/pleroma/web/plugs/frontend_static_plug_test.exs +++ b/test/pleroma/web/plugs/frontend_static_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.FrontendStaticPlugTest do @@ -74,4 +74,35 @@ defmodule Pleroma.Web.Plugs.FrontendStaticPlugTest do        assert %Plug.Conn{status: :success} = get(conn, url)      end    end + +  test "api routes are detected correctly" do +    # If this test fails we have probably added something +    # new that should be in /api/ instead +    expected_routes = [ +      "api", +      "main", +      "ostatus_subscribe", +      "oauth", +      "objects", +      "activities", +      "notice", +      "users", +      "tags", +      "mailer", +      "inbox", +      "relay", +      "internal", +      ".well-known", +      "nodeinfo", +      "web", +      "auth", +      "embed", +      "proxy", +      "test", +      "user_exists", +      "check_password" +    ] + +    assert expected_routes == Pleroma.Web.get_api_routes() +  end  end diff --git a/test/pleroma/web/plugs/http_security_plug_test.exs b/test/pleroma/web/plugs/http_security_plug_test.exs index df2b5ebb3..4e7befdd5 100644 --- a/test/pleroma/web/plugs/http_security_plug_test.exs +++ b/test/pleroma/web/plugs/http_security_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.HTTPSecurityPlugTest do @@ -72,6 +72,21 @@ defmodule Pleroma.Web.Plugs.HTTPSecurityPlugTest do        assert csp =~ "media-src 'self' https:;"        assert csp =~ "img-src 'self' data: blob: https:;"      end + +    test "it sets the Service-Worker-Allowed header", %{conn: conn} do +      clear_config([:http_security, :enabled], true) +      clear_config([:frontends, :primary], %{"name" => "fedi-fe", "ref" => "develop"}) + +      clear_config([:frontends, :available], %{ +        "fedi-fe" => %{ +          "name" => "fedi-fe", +          "custom-http-headers" => [{"service-worker-allowed", "/"}] +        } +      }) + +      conn = get(conn, "/api/v1/instance") +      assert Conn.get_resp_header(conn, "service-worker-allowed") == ["/"] +    end    end    describe "img-src and media-src" do diff --git a/test/pleroma/web/plugs/http_signature_plug_test.exs b/test/pleroma/web/plugs/http_signature_plug_test.exs index e6cbde803..56ef6b06f 100644 --- a/test/pleroma/web/plugs/http_signature_plug_test.exs +++ b/test/pleroma/web/plugs/http_signature_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.HTTPSignaturePlugTest do @@ -32,11 +32,7 @@ defmodule Pleroma.Web.Plugs.HTTPSignaturePlugTest do    describe "requires a signature when `authorized_fetch_mode` is enabled" do      setup do -      Pleroma.Config.put([:activitypub, :authorized_fetch_mode], true) - -      on_exit(fn -> -        Pleroma.Config.put([:activitypub, :authorized_fetch_mode], false) -      end) +      clear_config([:activitypub, :authorized_fetch_mode], true)        params = %{"actor" => "http://mastodon.example.org/users/admin"}        conn = build_conn(:get, "/doesntmattter", params) |> put_format("activity+json") diff --git a/test/pleroma/web/plugs/idempotency_plug_test.exs b/test/pleroma/web/plugs/idempotency_plug_test.exs index 4a7835993..dd8cda664 100644 --- a/test/pleroma/web/plugs/idempotency_plug_test.exs +++ b/test/pleroma/web/plugs/idempotency_plug_test.exs @@ -1,9 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.IdempotencyPlugTest do -  use ExUnit.Case, async: true +  # Relies on Cachex, has to stay synchronous +  use Pleroma.DataCase    use Plug.Test    alias Pleroma.Web.Plugs.IdempotencyPlug diff --git a/test/pleroma/web/plugs/instance_static_test.exs b/test/pleroma/web/plugs/instance_static_test.exs index 5b30011d3..46f2ca6b1 100644 --- a/test/pleroma/web/plugs/instance_static_test.exs +++ b/test/pleroma/web/plugs/instance_static_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.InstanceStaticTest do diff --git a/test/pleroma/web/plugs/mapped_signature_to_identity_plug_test.exs b/test/pleroma/web/plugs/mapped_signature_to_identity_plug_test.exs index 0ad3c2929..00ce6492d 100644 --- a/test/pleroma/web/plugs/mapped_signature_to_identity_plug_test.exs +++ b/test/pleroma/web/plugs/mapped_signature_to_identity_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.MappedSignatureToIdentityPlugTest do diff --git a/test/pleroma/web/plugs/o_auth_plug_test.exs b/test/pleroma/web/plugs/o_auth_plug_test.exs index 1186cdb14..9e4be5559 100644 --- a/test/pleroma/web/plugs/o_auth_plug_test.exs +++ b/test/pleroma/web/plugs/o_auth_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.OAuthPlugTest do diff --git a/test/pleroma/web/plugs/o_auth_scopes_plug_test.exs b/test/pleroma/web/plugs/o_auth_scopes_plug_test.exs index 982a70bf9..9f6d3dc71 100644 --- a/test/pleroma/web/plugs/o_auth_scopes_plug_test.exs +++ b/test/pleroma/web/plugs/o_auth_scopes_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.OAuthScopesPlugTest do @@ -169,42 +169,4 @@ defmodule Pleroma.Web.Plugs.OAuthScopesPlugTest do        assert f.(["admin:read"], ["write", "admin"]) == ["admin:read"]      end    end - -  describe "transform_scopes/2" do -    setup do: clear_config([:auth, :enforce_oauth_admin_scope_usage]) - -    setup do -      {:ok, %{f: &OAuthScopesPlug.transform_scopes/2}} -    end - -    test "with :admin option, prefixes all requested scopes with `admin:` " <> -           "and [optionally] keeps only prefixed scopes, " <> -           "depending on `[:auth, :enforce_oauth_admin_scope_usage]` setting", -         %{f: f} do -      Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], false) - -      assert f.(["read"], %{admin: true}) == ["admin:read", "read"] - -      assert f.(["read", "write"], %{admin: true}) == [ -               "admin:read", -               "read", -               "admin:write", -               "write" -             ] - -      Pleroma.Config.put([:auth, :enforce_oauth_admin_scope_usage], true) - -      assert f.(["read:accounts"], %{admin: true}) == ["admin:read:accounts"] - -      assert f.(["read", "write:reports"], %{admin: true}) == [ -               "admin:read", -               "admin:write:reports" -             ] -    end - -    test "with no supported options, returns unmodified scopes", %{f: f} do -      assert f.(["read"], %{}) == ["read"] -      assert f.(["read", "write"], %{}) == ["read", "write"] -    end -  end  end diff --git a/test/pleroma/web/plugs/plug_helper_test.exs b/test/pleroma/web/plugs/plug_helper_test.exs index 670d699f0..346113628 100644 --- a/test/pleroma/web/plugs/plug_helper_test.exs +++ b/test/pleroma/web/plugs/plug_helper_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.PlugHelperTest do diff --git a/test/pleroma/web/plugs/rate_limiter_test.exs b/test/pleroma/web/plugs/rate_limiter_test.exs index 249c78b37..d007e3f26 100644 --- a/test/pleroma/web/plugs/rate_limiter_test.exs +++ b/test/pleroma/web/plugs/rate_limiter_test.exs @@ -1,12 +1,11 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.RateLimiterTest do    use Pleroma.Web.ConnCase    alias Phoenix.ConnTest -  alias Pleroma.Config    alias Pleroma.Web.Plugs.RateLimiter    alias Plug.Conn @@ -22,8 +21,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do      setup do: clear_config([Pleroma.Web.Plugs.RemoteIp, :enabled])      test "config is required for plug to work" do -      Config.put([:rate_limit, @limiter_name], {1, 1}) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +      clear_config([:rate_limit, @limiter_name], {1, 1}) +      clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})        assert %{limits: {1, 1}, name: :test_init, opts: [name: :test_init]} ==                 [name: @limiter_name] @@ -54,8 +53,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do      scale = 80      limit = 5 -    Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) -    Config.put([:rate_limit, limiter_name], {scale, limit}) +    clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +    clear_config([:rate_limit, limiter_name], {scale, limit})      plug_opts = RateLimiter.init(name: limiter_name)      conn = build_conn(:get, "/") @@ -86,8 +85,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do      test "`bucket_name` option overrides default bucket name" do        limiter_name = :test_bucket_name -      Config.put([:rate_limit, limiter_name], {1000, 5}) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +      clear_config([:rate_limit, limiter_name], {1000, 5}) +      clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})        base_bucket_name = "#{limiter_name}:group1"        plug_opts = RateLimiter.init(name: limiter_name, bucket_name: base_bucket_name) @@ -101,8 +100,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do      test "`params` option allows different queries to be tracked independently" do        limiter_name = :test_params -      Config.put([:rate_limit, limiter_name], {1000, 5}) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +      clear_config([:rate_limit, limiter_name], {1000, 5}) +      clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})        plug_opts = RateLimiter.init(name: limiter_name, params: ["id"]) @@ -117,8 +116,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do      test "it supports combination of options modifying bucket name" do        limiter_name = :test_options_combo -      Config.put([:rate_limit, limiter_name], {1000, 5}) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +      clear_config([:rate_limit, limiter_name], {1000, 5}) +      clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})        base_bucket_name = "#{limiter_name}:group1" @@ -140,8 +139,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do    describe "unauthenticated users" do      test "are restricted based on remote IP" do        limiter_name = :test_unauthenticated -      Config.put([:rate_limit, limiter_name], [{1000, 5}, {1, 10}]) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +      clear_config([:rate_limit, limiter_name], [{1000, 5}, {1, 10}]) +      clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})        plug_opts = RateLimiter.init(name: limiter_name) @@ -180,8 +179,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do        scale = 50        limit = 5 -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) -      Config.put([:rate_limit, limiter_name], [{1000, 1}, {scale, limit}]) +      clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +      clear_config([:rate_limit, limiter_name], [{1000, 1}, {scale, limit}])        plug_opts = RateLimiter.init(name: limiter_name) @@ -202,8 +201,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do      test "different users are counted independently" do        limiter_name = :test_authenticated2 -      Config.put([:rate_limit, limiter_name], [{1, 10}, {1000, 5}]) -      Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +      clear_config([:rate_limit, limiter_name], [{1, 10}, {1000, 5}]) +      clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})        plug_opts = RateLimiter.init(name: limiter_name) @@ -232,8 +231,8 @@ defmodule Pleroma.Web.Plugs.RateLimiterTest do    test "doesn't crash due to a race condition when multiple requests are made at the same time and the bucket is not yet initialized" do      limiter_name = :test_race_condition -    Pleroma.Config.put([:rate_limit, limiter_name], {1000, 5}) -    Pleroma.Config.put([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8}) +    clear_config([:rate_limit, limiter_name], {1000, 5}) +    clear_config([Pleroma.Web.Endpoint, :http, :ip], {8, 8, 8, 8})      opts = RateLimiter.init(name: limiter_name) diff --git a/test/pleroma/web/plugs/remote_ip_test.exs b/test/pleroma/web/plugs/remote_ip_test.exs index 0bdb4c168..4d98de2bd 100644 --- a/test/pleroma/web/plugs/remote_ip_test.exs +++ b/test/pleroma/web/plugs/remote_ip_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.RemoteIpTest do @@ -26,7 +26,7 @@ defmodule Pleroma.Web.Plugs.RemoteIpTest do            )    test "disabled" do -    Pleroma.Config.put(RemoteIp, enabled: false) +    clear_config(RemoteIp, enabled: false)      %{remote_ip: remote_ip} = conn(:get, "/") @@ -48,7 +48,7 @@ defmodule Pleroma.Web.Plugs.RemoteIpTest do    end    test "custom headers" do -    Pleroma.Config.put(RemoteIp, enabled: true, headers: ["cf-connecting-ip"]) +    clear_config(RemoteIp, enabled: true, headers: ["cf-connecting-ip"])      conn =        conn(:get, "/") @@ -73,7 +73,7 @@ defmodule Pleroma.Web.Plugs.RemoteIpTest do      refute conn.remote_ip == {1, 1, 1, 1} -    Pleroma.Config.put([RemoteIp, :proxies], ["173.245.48.0/20"]) +    clear_config([RemoteIp, :proxies], ["173.245.48.0/20"])      conn =        conn(:get, "/") @@ -84,7 +84,7 @@ defmodule Pleroma.Web.Plugs.RemoteIpTest do    end    test "proxies set without CIDR format" do -    Pleroma.Config.put([RemoteIp, :proxies], ["173.245.48.1"]) +    clear_config([RemoteIp, :proxies], ["173.245.48.1"])      conn =        conn(:get, "/") @@ -95,8 +95,8 @@ defmodule Pleroma.Web.Plugs.RemoteIpTest do    end    test "proxies set `nonsensical` CIDR" do -    Pleroma.Config.put([RemoteIp, :reserved], ["127.0.0.0/8"]) -    Pleroma.Config.put([RemoteIp, :proxies], ["10.0.0.3/24"]) +    clear_config([RemoteIp, :reserved], ["127.0.0.0/8"]) +    clear_config([RemoteIp, :proxies], ["10.0.0.3/24"])      conn =        conn(:get, "/") diff --git a/test/pleroma/web/plugs/set_format_plug_test.exs b/test/pleroma/web/plugs/set_format_plug_test.exs index e95d751fa..21043f698 100644 --- a/test/pleroma/web/plugs/set_format_plug_test.exs +++ b/test/pleroma/web/plugs/set_format_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.SetFormatPlugTest do diff --git a/test/pleroma/web/plugs/set_locale_plug_test.exs b/test/pleroma/web/plugs/set_locale_plug_test.exs index 773f48a5b..5261e67ae 100644 --- a/test/pleroma/web/plugs/set_locale_plug_test.exs +++ b/test/pleroma/web/plugs/set_locale_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.SetLocalePlugTest do diff --git a/test/pleroma/web/plugs/set_user_session_id_plug_test.exs b/test/pleroma/web/plugs/set_user_session_id_plug_test.exs index 21417d0e7..9814c80d8 100644 --- a/test/pleroma/web/plugs/set_user_session_id_plug_test.exs +++ b/test/pleroma/web/plugs/set_user_session_id_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.SetUserSessionIdPlugTest do diff --git a/test/pleroma/web/plugs/uploaded_media_plug_test.exs b/test/pleroma/web/plugs/uploaded_media_plug_test.exs index 7c8313121..75f313282 100644 --- a/test/pleroma/web/plugs/uploaded_media_plug_test.exs +++ b/test/pleroma/web/plugs/uploaded_media_plug_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.UploadedMediaPlugTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Upload    defp upload_file(context) do diff --git a/test/pleroma/web/plugs/user_enabled_plug_test.exs b/test/pleroma/web/plugs/user_enabled_plug_test.exs index 71c56f03a..999c6c49c 100644 --- a/test/pleroma/web/plugs/user_enabled_plug_test.exs +++ b/test/pleroma/web/plugs/user_enabled_plug_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.UserEnabledPlugTest do -  use Pleroma.Web.ConnCase, async: true +  use Pleroma.Web.ConnCase    alias Pleroma.Web.Plugs.UserEnabledPlug    import Pleroma.Factory @@ -20,9 +20,9 @@ defmodule Pleroma.Web.Plugs.UserEnabledPlugTest do    test "with a user that's not confirmed and a config requiring confirmation, it removes that user",         %{conn: conn} do -    Pleroma.Config.put([:instance, :account_activation_required], true) +    clear_config([:instance, :account_activation_required], true) -    user = insert(:user, confirmation_pending: true) +    user = insert(:user, is_confirmed: false)      conn =        conn @@ -33,7 +33,7 @@ defmodule Pleroma.Web.Plugs.UserEnabledPlugTest do    end    test "with a user that is deactivated, it removes that user", %{conn: conn} do -    user = insert(:user, deactivated: true) +    user = insert(:user, is_active: false)      conn =        conn diff --git a/test/pleroma/web/plugs/user_fetcher_plug_test.exs b/test/pleroma/web/plugs/user_fetcher_plug_test.exs index b4f875d2d..902bee642 100644 --- a/test/pleroma/web/plugs/user_fetcher_plug_test.exs +++ b/test/pleroma/web/plugs/user_fetcher_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.UserFetcherPlugTest do diff --git a/test/pleroma/web/plugs/user_is_admin_plug_test.exs b/test/pleroma/web/plugs/user_is_admin_plug_test.exs index b550568c1..58996d5a4 100644 --- a/test/pleroma/web/plugs/user_is_admin_plug_test.exs +++ b/test/pleroma/web/plugs/user_is_admin_plug_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Plugs.UserIsAdminPlugTest do diff --git a/test/pleroma/web/plugs/user_tracking_plug_test.exs b/test/pleroma/web/plugs/user_tracking_plug_test.exs new file mode 100644 index 000000000..8e9d59b99 --- /dev/null +++ b/test/pleroma/web/plugs/user_tracking_plug_test.exs @@ -0,0 +1,58 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.Plugs.UserTrackingPlugTest do +  use Pleroma.Web.ConnCase, async: true + +  import Pleroma.Factory + +  alias Pleroma.Web.Plugs.UserTrackingPlug + +  test "updates last_active_at for a new user", %{conn: conn} do +    user = insert(:user) + +    assert is_nil(user.last_active_at) + +    test_started_at = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + +    %{assigns: %{user: user}} = +      conn +      |> assign(:user, user) +      |> UserTrackingPlug.call(%{}) + +    assert user.last_active_at >= test_started_at +    assert user.last_active_at <= NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second) +  end + +  test "doesn't update last_active_at if it was updated recently", %{conn: conn} do +    last_active_at = +      NaiveDateTime.utc_now() +      |> NaiveDateTime.add(-:timer.hours(1), :millisecond) +      |> NaiveDateTime.truncate(:second) + +    user = insert(:user, %{last_active_at: last_active_at}) + +    %{assigns: %{user: user}} = +      conn +      |> assign(:user, user) +      |> UserTrackingPlug.call(%{}) + +    assert user.last_active_at == last_active_at +  end + +  test "skips updating last_active_at if user ID is nil", %{conn: conn} do +    %{assigns: %{user: user}} = +      conn +      |> assign(:user, %Pleroma.User{}) +      |> UserTrackingPlug.call(%{}) + +    assert is_nil(user.last_active_at) +  end + +  test "does nothing if user is not present", %{conn: conn} do +    %{assigns: assigns} = UserTrackingPlug.call(conn, %{}) + +    refute Map.has_key?(assigns, :user) +  end +end diff --git a/test/pleroma/web/preload/providers/instance_test.exs b/test/pleroma/web/preload/providers/instance_test.exs index 8493f2a94..a401475ee 100644 --- a/test/pleroma/web/preload/providers/instance_test.exs +++ b/test/pleroma/web/preload/providers/instance_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Preload.Providers.InstanceTest do @@ -50,7 +50,7 @@ defmodule Pleroma.Web.Preload.Providers.InstanceTest do      "/api/pleroma/frontend_configurations" => fe_configs    } do      assert %{ -             pleroma_fe: %{background: "/images/city.jpg", logo: "/static/logo.png"} +             pleroma_fe: %{background: "/images/city.jpg", logo: "/static/logo.svg"}             } = fe_configs    end  end diff --git a/test/pleroma/web/preload/providers/timeline_test.exs b/test/pleroma/web/preload/providers/timeline_test.exs index 3b1f2f1aa..2ae2ca5fb 100644 --- a/test/pleroma/web/preload/providers/timeline_test.exs +++ b/test/pleroma/web/preload/providers/timeline_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Preload.Providers.TimelineTest do diff --git a/test/pleroma/web/preload/providers/user_test.exs b/test/pleroma/web/preload/providers/user_test.exs index 83f065e27..b7017ac20 100644 --- a/test/pleroma/web/preload/providers/user_test.exs +++ b/test/pleroma/web/preload/providers/user_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Preload.Providers.UserTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Web.Preload.Providers.User diff --git a/test/pleroma/web/push/impl_test.exs b/test/pleroma/web/push/impl_test.exs index 2a4a8fd06..b3ca1a337 100644 --- a/test/pleroma/web/push/impl_test.exs +++ b/test/pleroma/web/push/impl_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.Push.ImplTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory @@ -118,7 +118,7 @@ defmodule Pleroma.Web.Push.ImplTest do            "<span>Lorem ipsum dolor sit amet</span>, consectetur :firefox: adipiscing elit. Fusce sagittis finibus turpis."        }) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert Impl.format_body(               %{ @@ -137,7 +137,7 @@ defmodule Pleroma.Web.Push.ImplTest do      user = insert(:user, nickname: "Bob")      other_user = insert(:user)      {:ok, _, _, activity} = CommonAPI.follow(user, other_user) -    object = Object.normalize(activity, false) +    object = Object.normalize(activity, fetch: false)      assert Impl.format_body(%{activity: activity, type: "follow"}, user, object) ==               "@Bob has followed you" @@ -156,7 +156,7 @@ defmodule Pleroma.Web.Push.ImplTest do        })      {:ok, announce_activity} = CommonAPI.repeat(activity.id, user) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert Impl.format_body(%{activity: announce_activity}, user, object) ==               "@#{user.nickname} repeated: Lorem ipsum dolor sit amet, consectetur  adipiscing elit. Fusce sagittis fini..." @@ -175,7 +175,7 @@ defmodule Pleroma.Web.Push.ImplTest do        })      {:ok, activity} = CommonAPI.favorite(user, activity.id) -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert Impl.format_body(%{activity: activity, type: "favourite"}, user, object) ==               "@Bob has favorited your post" @@ -193,7 +193,7 @@ defmodule Pleroma.Web.Push.ImplTest do        })      {:ok, activity} = CommonAPI.react_with_emoji(activity.id, user, "👍") -    object = Object.normalize(activity) +    object = Object.normalize(activity, fetch: false)      assert Impl.format_body(%{activity: activity, type: "pleroma:emoji_reaction"}, user, object) ==               "@Bob reacted with 👍" @@ -221,7 +221,7 @@ defmodule Pleroma.Web.Push.ImplTest do        recipient = insert(:user)        {:ok, chat} = CommonAPI.post_chat_message(user, recipient, "hey") -      object = Object.normalize(chat, false) +      object = Object.normalize(chat, fetch: false)        [notification] = Notification.for_user(recipient)        res = Impl.build_content(notification, user, object) @@ -245,7 +245,7 @@ defmodule Pleroma.Web.Push.ImplTest do        {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)        {:ok, chat} = CommonAPI.post_chat_message(user, recipient, nil, media_id: upload.id) -      object = Object.normalize(chat, false) +      object = Object.normalize(chat, fetch: false)        [notification] = Notification.for_user(recipient)        res = Impl.build_content(notification, user, object) @@ -271,7 +271,7 @@ defmodule Pleroma.Web.Push.ImplTest do        notif = insert(:notification, user: user2, activity: activity)        actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert Impl.build_content(notif, actor, object) == %{                 body: "New Direct Message" @@ -286,7 +286,7 @@ defmodule Pleroma.Web.Push.ImplTest do        notif = insert(:notification, user: user2, activity: activity, type: "mention")        actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert Impl.build_content(notif, actor, object) == %{                 body: "New Mention" @@ -297,7 +297,7 @@ defmodule Pleroma.Web.Push.ImplTest do        notif = insert(:notification, user: user2, activity: activity, type: "favourite")        actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert Impl.build_content(notif, actor, object) == %{                 body: "New Favorite" @@ -320,7 +320,7 @@ defmodule Pleroma.Web.Push.ImplTest do        notif = insert(:notification, user: user2, activity: activity)        actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert Impl.build_content(notif, actor, object) == %{                 body: @@ -338,7 +338,7 @@ defmodule Pleroma.Web.Push.ImplTest do        notif = insert(:notification, user: user2, activity: activity, type: "mention")        actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert Impl.build_content(notif, actor, object) == %{                 body: @@ -351,7 +351,7 @@ defmodule Pleroma.Web.Push.ImplTest do        notif = insert(:notification, user: user2, activity: activity, type: "favourite")        actor = User.get_cached_by_ap_id(notif.activity.data["actor"]) -      object = Object.normalize(activity) +      object = Object.normalize(activity, fetch: false)        assert Impl.build_content(notif, actor, object) == %{                 body: "@Bob has favorited your post", diff --git a/test/pleroma/web/rel_me_test.exs b/test/pleroma/web/rel_me_test.exs index 65255916d..313b163b5 100644 --- a/test/pleroma/web/rel_me_test.exs +++ b/test/pleroma/web/rel_me_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.RelMeTest do -  use ExUnit.Case +  use Pleroma.DataCase    setup_all do      Tesla.Mock.mock_global(fn env -> apply(HttpRequestMock, :request, [env]) end) diff --git a/test/pleroma/web/rich_media/helpers_test.exs b/test/pleroma/web/rich_media/helpers_test.exs index 4c9ee77d0..689854fb6 100644 --- a/test/pleroma/web/rich_media/helpers_test.exs +++ b/test/pleroma/web/rich_media/helpers_test.exs @@ -1,11 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.RichMedia.HelpersTest do    use Pleroma.DataCase -  alias Pleroma.Config    alias Pleroma.Web.CommonAPI    alias Pleroma.Web.RichMedia.Helpers @@ -29,7 +28,7 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do          content_type: "text/markdown"        }) -    Config.put([:rich_media, :enabled], true) +    clear_config([:rich_media, :enabled], true)      assert %{} == Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity)    end @@ -43,7 +42,7 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do          content_type: "text/markdown"        }) -    Config.put([:rich_media, :enabled], true) +    clear_config([:rich_media, :enabled], true)      assert %{} == Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity)    end @@ -57,7 +56,7 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do          content_type: "text/markdown"        }) -    Config.put([:rich_media, :enabled], true) +    clear_config([:rich_media, :enabled], true)      assert %{page_url: "https://example.com/ogp", rich_media: _} =               Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity) @@ -74,7 +73,7 @@ defmodule Pleroma.Web.RichMedia.HelpersTest do      {:ok, activity4} = CommonAPI.post(user, %{status: "https://192.168.10.40/notice/9kCP7V"})      {:ok, activity5} = CommonAPI.post(user, %{status: "https://pleroma.local/notice/9kCP7V"}) -    Config.put([:rich_media, :enabled], true) +    clear_config([:rich_media, :enabled], true)      assert %{} = Helpers.fetch_data_for_activity(activity)      assert %{} = Helpers.fetch_data_for_activity(activity2) diff --git a/test/pleroma/web/rich_media/parser/ttl/aws_signed_url_test.exs b/test/pleroma/web/rich_media/parser/ttl/aws_signed_url_test.exs index 2f17bebd7..df3ea3e99 100644 --- a/test/pleroma/web/rich_media/parser/ttl/aws_signed_url_test.exs +++ b/test/pleroma/web/rich_media/parser/ttl/aws_signed_url_test.exs @@ -1,9 +1,10 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.RichMedia.Parser.TTL.AwsSignedUrlTest do -  use ExUnit.Case, async: true +  # Relies on Cachex, needs to be synchronous +  use Pleroma.DataCase    test "s3 signed url is parsed correct for expiration time" do      url = "https://pleroma.social/amz" diff --git a/test/pleroma/web/rich_media/parser_test.exs b/test/pleroma/web/rich_media/parser_test.exs index 6d00c2af5..2f363b012 100644 --- a/test/pleroma/web/rich_media/parser_test.exs +++ b/test/pleroma/web/rich_media/parser_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.RichMedia.ParserTest do diff --git a/test/pleroma/web/rich_media/parsers/twitter_card_test.exs b/test/pleroma/web/rich_media/parsers/twitter_card_test.exs index 219f005a2..2aacd29a3 100644 --- a/test/pleroma/web/rich_media/parsers/twitter_card_test.exs +++ b/test/pleroma/web/rich_media/parsers/twitter_card_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.RichMedia.Parsers.TwitterCardTest do diff --git a/test/pleroma/web/static_fe/static_fe_controller_test.exs b/test/pleroma/web/static_fe/static_fe_controller_test.exs index 19506f1d8..2af14dfeb 100644 --- a/test/pleroma/web/static_fe/static_fe_controller_test.exs +++ b/test/pleroma/web/static_fe/static_fe_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.StaticFE.StaticFEControllerTest do diff --git a/test/pleroma/web/streamer_test.exs b/test/pleroma/web/streamer_test.exs index ad66ddc9d..b788a9138 100644 --- a/test/pleroma/web/streamer_test.exs +++ b/test/pleroma/web/streamer_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.StreamerTest do @@ -266,7 +266,7 @@ defmodule Pleroma.Web.StreamerTest do        {:ok, create_activity} =          CommonAPI.post_chat_message(other_user, user, "hey cirno", idempotency_key: "123") -      object = Object.normalize(create_activity, false) +      object = Object.normalize(create_activity, fetch: false)        chat = Chat.get(user.id, other_user.ap_id)        cm_ref = MessageReference.for_chat_and_object(chat, object)        cm_ref = %{cm_ref | chat: chat, object: object} @@ -284,7 +284,7 @@ defmodule Pleroma.Web.StreamerTest do        other_user = insert(:user)        {:ok, create_activity} = CommonAPI.post_chat_message(other_user, user, "hey cirno") -      object = Object.normalize(create_activity, false) +      object = Object.normalize(create_activity, fetch: false)        chat = Chat.get(user.id, other_user.ap_id)        cm_ref = MessageReference.for_chat_and_object(chat, object)        cm_ref = %{cm_ref | chat: chat, object: object} @@ -383,19 +383,8 @@ defmodule Pleroma.Web.StreamerTest do        user: user,        token: oauth_token      } do -      user_url = user.ap_id        user2 = insert(:user) -      body = -        File.read!("test/fixtures/users_mock/localhost.json") -        |> String.replace("{{nickname}}", user.nickname) -        |> Jason.encode!() - -      Tesla.Mock.mock_global(fn -        %{method: :get, url: ^user_url} -> -          %Tesla.Env{status: 200, body: body} -      end) -        Streamer.get_topic_and_add_socket("user:notification", user, oauth_token)        {:ok, _follower, _followed, follow_activity} = CommonAPI.follow(user2, user) @@ -409,20 +398,9 @@ defmodule Pleroma.Web.StreamerTest do        token: oauth_token      } do        user_id = user.id -      user_url = user.ap_id        other_user = insert(:user)        other_user_id = other_user.id -      body = -        File.read!("test/fixtures/users_mock/localhost.json") -        |> String.replace("{{nickname}}", user.nickname) -        |> Jason.encode!() - -      Tesla.Mock.mock_global(fn -        %{method: :get, url: ^user_url} -> -          %Tesla.Env{status: 200, body: body} -      end) -        Streamer.get_topic_and_add_socket("user", user, oauth_token)        {:ok, _follower, _followed, _follow_activity} = CommonAPI.follow(user, other_user) @@ -510,7 +488,7 @@ defmodule Pleroma.Web.StreamerTest do    describe "thread_containment/2" do      test "it filters to user if recipients invalid and thread containment is enabled" do -      Pleroma.Config.put([:instance, :skip_thread_containment], false) +      clear_config([:instance, :skip_thread_containment], false)        author = insert(:user)        %{user: user, token: oauth_token} = oauth_access(["read"])        User.follow(user, author, :follow_accept) @@ -531,7 +509,7 @@ defmodule Pleroma.Web.StreamerTest do      end      test "it sends message if recipients invalid and thread containment is disabled" do -      Pleroma.Config.put([:instance, :skip_thread_containment], true) +      clear_config([:instance, :skip_thread_containment], true)        author = insert(:user)        %{user: user, token: oauth_token} = oauth_access(["read"])        User.follow(user, author, :follow_accept) @@ -553,7 +531,7 @@ defmodule Pleroma.Web.StreamerTest do      end      test "it sends message if recipients invalid and thread containment is enabled but user's thread containment is disabled" do -      Pleroma.Config.put([:instance, :skip_thread_containment], false) +      clear_config([:instance, :skip_thread_containment], false)        author = insert(:user)        user = insert(:user, skip_thread_containment: true)        %{token: oauth_token} = oauth_access(["read"], user: user) diff --git a/test/pleroma/web/twitter_api/controller_test.exs b/test/pleroma/web/twitter_api/controller_test.exs index 464d0ea2e..583c904b2 100644 --- a/test/pleroma/web/twitter_api/controller_test.exs +++ b/test/pleroma/web/twitter_api/controller_test.exs @@ -1,13 +1,13 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.TwitterAPI.ControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true -  alias Pleroma.Builders.ActivityBuilder    alias Pleroma.Repo    alias Pleroma.User +  alias Pleroma.Web.CommonAPI    alias Pleroma.Web.OAuth.Token    import Pleroma.Factory @@ -36,22 +36,20 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do        other_user = insert(:user)        {:ok, _activity} = -        ActivityBuilder.insert(%{"to" => [current_user.ap_id]}, %{user: other_user}) +        CommonAPI.post(other_user, %{ +          status: "Hey @#{current_user.nickname}" +        })        response_conn =          conn -        |> assign(:user, current_user)          |> get("/api/v1/notifications") -      [notification] = response = json_response(response_conn, 200) - -      assert length(response) == 1 +      [notification] = json_response(response_conn, 200)        assert notification["pleroma"]["is_seen"] == false        response_conn =          conn -        |> assign(:user, current_user)          |> post("/api/qvitter/statuses/notifications/read", %{"latest_id" => notification["id"]})        [notification] = response = json_response(response_conn, 200) @@ -66,10 +64,10 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do      setup do        {:ok, user} =          insert(:user) -        |> User.confirmation_changeset(need_confirmation: true) +        |> User.confirmation_changeset(set_confirmation: false)          |> Repo.update() -      assert user.confirmation_pending +      refute user.is_confirmed        [user: user]      end @@ -85,7 +83,7 @@ defmodule Pleroma.Web.TwitterAPI.ControllerTest do        user = User.get_cached_by_id(user.id) -      refute user.confirmation_pending +      assert user.is_confirmed        refute user.confirmation_token      end diff --git a/test/pleroma/web/twitter_api/password_controller_test.exs b/test/pleroma/web/twitter_api/password_controller_test.exs index 6d08075cc..cf99e2434 100644 --- a/test/pleroma/web/twitter_api/password_controller_test.exs +++ b/test/pleroma/web/twitter_api/password_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.TwitterAPI.PasswordControllerTest do @@ -37,8 +37,7 @@ defmodule Pleroma.Web.TwitterAPI.PasswordControllerTest do        user = insert(:user)        {:ok, token} = PasswordResetToken.create_token(user) - -      :timer.sleep(2000) +      {:ok, token} = time_travel(token, -2)        response =          conn @@ -55,7 +54,7 @@ defmodule Pleroma.Web.TwitterAPI.PasswordControllerTest do        user = insert(:user)        {:ok, token} = PasswordResetToken.create_token(user) -      :timer.sleep(2000) +      {:ok, token} = time_travel(token, -2)        {:ok, _access_token} = Token.create(insert(:oauth_app), user, %{})        params = %{ @@ -93,7 +92,7 @@ defmodule Pleroma.Web.TwitterAPI.PasswordControllerTest do        assert response =~ "<h2>Password changed!</h2>"        user = refresh_record(user) -      assert Pbkdf2.verify_pass("test", user.password_hash) +      assert Pleroma.Password.Pbkdf2.verify_pass("test", user.password_hash)        assert Enum.empty?(Token.get_user_tokens(user))      end diff --git a/test/pleroma/web/twitter_api/remote_follow_controller_test.exs b/test/pleroma/web/twitter_api/remote_follow_controller_test.exs index a3e784d13..fa3b29006 100644 --- a/test/pleroma/web/twitter_api/remote_follow_controller_test.exs +++ b/test/pleroma/web/twitter_api/remote_follow_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do @@ -14,18 +14,37 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do    import Pleroma.Factory    import Ecto.Query -  setup do -    Tesla.Mock.mock(fn env -> apply(HttpRequestMock, :request, [env]) end) -    :ok -  end -    setup_all do: clear_config([:instance, :federating], true) -  setup do: clear_config([:instance]) -  setup do: clear_config([:frontend_configurations, :pleroma_fe])    setup do: clear_config([:user, :deny_follow_blocked])    describe "GET /ostatus_subscribe - remote_follow/2" do      test "adds status to pleroma instance if the `acct` is a status", %{conn: conn} do +      Tesla.Mock.mock(fn +        %{method: :get, url: "https://mastodon.social/users/emelie/statuses/101849165031453009"} -> +          %Tesla.Env{ +            status: 200, +            headers: [{"content-type", "application/activity+json"}], +            body: File.read!("test/fixtures/tesla_mock/status.emelie.json") +          } + +        %{method: :get, url: "https://mastodon.social/users/emelie/collections/featured"} -> +          %Tesla.Env{ +            status: 200, +            headers: [{"content-type", "application/activity+json"}], +            body: +              File.read!("test/fixtures/users_mock/masto_featured.json") +              |> String.replace("{{domain}}", "mastodon.social") +              |> String.replace("{{nickname}}", "emelie") +          } + +        %{method: :get, url: "https://mastodon.social/users/emelie"} -> +          %Tesla.Env{ +            status: 200, +            headers: [{"content-type", "application/activity+json"}], +            body: File.read!("test/fixtures/tesla_mock/emelie.json") +          } +      end) +        assert conn               |> get(                 remote_follow_path(conn, :follow, %{ @@ -36,6 +55,25 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do      end      test "show follow account page if the `acct` is a account link", %{conn: conn} do +      Tesla.Mock.mock(fn +        %{method: :get, url: "https://mastodon.social/users/emelie"} -> +          %Tesla.Env{ +            status: 200, +            headers: [{"content-type", "application/activity+json"}], +            body: File.read!("test/fixtures/tesla_mock/emelie.json") +          } + +        %{method: :get, url: "https://mastodon.social/users/emelie/collections/featured"} -> +          %Tesla.Env{ +            status: 200, +            headers: [{"content-type", "application/activity+json"}], +            body: +              File.read!("test/fixtures/users_mock/masto_featured.json") +              |> String.replace("{{domain}}", "mastodon.social") +              |> String.replace("{{nickname}}", "emelie") +          } +      end) +        response =          conn          |> get(remote_follow_path(conn, :follow, %{acct: "https://mastodon.social/users/emelie"})) @@ -45,6 +83,25 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do      end      test "show follow page if the `acct` is a account link", %{conn: conn} do +      Tesla.Mock.mock(fn +        %{method: :get, url: "https://mastodon.social/users/emelie"} -> +          %Tesla.Env{ +            status: 200, +            headers: [{"content-type", "application/activity+json"}], +            body: File.read!("test/fixtures/tesla_mock/emelie.json") +          } + +        %{method: :get, url: "https://mastodon.social/users/emelie/collections/featured"} -> +          %Tesla.Env{ +            status: 200, +            headers: [{"content-type", "application/activity+json"}], +            body: +              File.read!("test/fixtures/users_mock/masto_featured.json") +              |> String.replace("{{domain}}", "mastodon.social") +              |> String.replace("{{nickname}}", "emelie") +          } +      end) +        user = insert(:user)        response = @@ -56,7 +113,14 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do        assert response =~ "Remote follow"      end -    test "show follow page with error when user cannot fecth by `acct` link", %{conn: conn} do +    test "show follow page with error when user can not be fetched by `acct` link", %{conn: conn} do +      Tesla.Mock.mock(fn +        %{method: :get, url: "https://mastodon.social/users/not_found"} -> +          %Tesla.Env{ +            status: 404 +          } +      end) +        user = insert(:user)        assert capture_log(fn -> @@ -107,7 +171,7 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do      end      test "returns error when user is deactivated", %{conn: conn} do -      user = insert(:user, deactivated: true) +      user = insert(:user, is_active: false)        user2 = insert(:user)        response = @@ -120,7 +184,7 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do      end      test "returns error when user is blocked", %{conn: conn} do -      Pleroma.Config.put([:user, :deny_follow_blocked], true) +      clear_config([:user, :deny_follow_blocked], true)        user = insert(:user)        user2 = insert(:user) @@ -331,7 +395,7 @@ defmodule Pleroma.Web.TwitterAPI.RemoteFollowControllerTest do      end      test "returns error when user is blocked", %{conn: conn} do -      Pleroma.Config.put([:user, :deny_follow_blocked], true) +      clear_config([:user, :deny_follow_blocked], true)        user = insert(:user)        user2 = insert(:user)        {:ok, _user_block} = Pleroma.User.block(user2, user) diff --git a/test/pleroma/web/twitter_api/twitter_api_test.exs b/test/pleroma/web/twitter_api/twitter_api_test.exs index 20a45cb6f..85629be04 100644 --- a/test/pleroma/web/twitter_api/twitter_api_test.exs +++ b/test/pleroma/web/twitter_api/twitter_api_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do @@ -46,12 +46,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do    end    test "it sends confirmation email if :account_activation_required is specified in instance config" do -    setting = Pleroma.Config.get([:instance, :account_activation_required]) - -    unless setting do -      Pleroma.Config.put([:instance, :account_activation_required], true) -      on_exit(fn -> Pleroma.Config.put([:instance, :account_activation_required], setting) end) -    end +    clear_config([:instance, :account_activation_required], true)      data = %{        :username => "lain", @@ -65,7 +60,7 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:ok, user} = TwitterAPI.register_user(data)      ObanHelpers.perform_all() -    assert user.confirmation_pending +    refute user.is_confirmed      email = Pleroma.Emails.UserEmail.account_confirmation_email(user) @@ -80,13 +75,9 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do    end    test "it sends an admin email if :account_approval_required is specified in instance config" do -    admin = insert(:user, is_admin: true) -    setting = Pleroma.Config.get([:instance, :account_approval_required]) +    clear_config([:instance, :account_approval_required], true) -    unless setting do -      Pleroma.Config.put([:instance, :account_approval_required], true) -      on_exit(fn -> Pleroma.Config.put([:instance, :account_approval_required], setting) end) -    end +    admin = insert(:user, is_admin: true)      data = %{        :username => "lain", @@ -101,17 +92,26 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      {:ok, user} = TwitterAPI.register_user(data)      ObanHelpers.perform_all() -    assert user.approval_pending +    refute user.is_approved -    email = Pleroma.Emails.AdminEmail.new_unapproved_registration(admin, user) +    user_email = Pleroma.Emails.UserEmail.approval_pending_email(user) +    admin_email = Pleroma.Emails.AdminEmail.new_unapproved_registration(admin, user)      notify_email = Pleroma.Config.get([:instance, :notify_email])      instance_name = Pleroma.Config.get([:instance, :name]) +    # User approval email +    Swoosh.TestAssertions.assert_email_sent( +      from: {instance_name, notify_email}, +      to: {user.name, user.email}, +      html_body: user_email.html_body +    ) + +    # Admin email      Swoosh.TestAssertions.assert_email_sent(        from: {instance_name, notify_email},        to: {admin.name, admin.email}, -      html_body: email.html_body +      html_body: admin_email.html_body      )    end @@ -423,10 +423,4 @@ defmodule Pleroma.Web.TwitterAPI.TwitterAPITest do      assert is_binary(error)      refute User.get_cached_by_nickname("lain")    end - -  setup do -    Supervisor.terminate_child(Pleroma.Supervisor, Cachex) -    Supervisor.restart_child(Pleroma.Supervisor, Cachex) -    :ok -  end  end diff --git a/test/pleroma/web/twitter_api/util_controller_test.exs b/test/pleroma/web/twitter_api/util_controller_test.exs index 60f2fb052..bdbc478c3 100644 --- a/test/pleroma/web/twitter_api/util_controller_test.exs +++ b/test/pleroma/web/twitter_api/util_controller_test.exs @@ -1,12 +1,11 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do    use Pleroma.Web.ConnCase    use Oban.Testing, repo: Pleroma.Repo -  alias Pleroma.Config    alias Pleroma.Tests.ObanHelpers    alias Pleroma.User @@ -66,7 +65,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do          }        ] -      Config.put(:frontend_configurations, config) +      clear_config(:frontend_configurations, config)        response =          conn @@ -99,7 +98,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      setup do: clear_config([:instance, :healthcheck])      test "returns 503 when healthcheck disabled", %{conn: conn} do -      Config.put([:instance, :healthcheck], false) +      clear_config([:instance, :healthcheck], false)        response =          conn @@ -110,7 +109,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      end      test "returns 200 when healthcheck enabled and all ok", %{conn: conn} do -      Config.put([:instance, :healthcheck], true) +      clear_config([:instance, :healthcheck], true)        with_mock Pleroma.Healthcheck,          system_info: fn -> %Pleroma.Healthcheck{healthy: true} end do @@ -130,7 +129,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do      end      test "returns 503 when healthcheck enabled and health is false", %{conn: conn} do -      Config.put([:instance, :healthcheck], true) +      clear_config([:instance, :healthcheck], true)        with_mock Pleroma.Healthcheck,          system_info: fn -> %Pleroma.Healthcheck{healthy: false} end do @@ -164,7 +163,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do        user = User.get_cached_by_id(user.id) -      assert user.deactivated == true +      refute user.is_active      end      test "with valid permissions and invalid password, it returns an error", %{conn: conn} do @@ -178,7 +177,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do        assert response == %{"error" => "Invalid password."}        user = User.get_cached_by_id(user.id) -      refute user.deactivated +      assert user.is_active      end    end @@ -397,7 +396,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do        assert json_response(conn, 200) == %{"status" => "success"}        fetched_user = User.get_cached_by_id(user.id) -      assert Pbkdf2.verify_pass("newpass", fetched_user.password_hash) == true +      assert Pleroma.Password.Pbkdf2.verify_pass("newpass", fetched_user.password_hash) == true      end    end @@ -428,7 +427,7 @@ defmodule Pleroma.Web.TwitterAPI.UtilControllerTest do        assert json_response(conn, 200) == %{"status" => "success"}        user = User.get_by_id(user.id) -      assert user.deactivated == true +      refute user.is_active        assert user.name == nil        assert user.bio == ""        assert user.password_hash == nil diff --git a/test/pleroma/web/uploader_controller_test.exs b/test/pleroma/web/uploader_controller_test.exs index 21e518236..fc278004e 100644 --- a/test/pleroma/web/uploader_controller_test.exs +++ b/test/pleroma/web/uploader_controller_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.UploaderControllerTest do -  use Pleroma.Web.ConnCase +  use Pleroma.Web.ConnCase, async: true    alias Pleroma.Uploaders.Uploader    describe "callback/2" do diff --git a/test/pleroma/web/views/error_view_test.exs b/test/pleroma/web/views/error_view_test.exs index 8dbbd18b4..42da8f458 100644 --- a/test/pleroma/web/views/error_view_test.exs +++ b/test/pleroma/web/views/error_view_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ErrorViewTest do diff --git a/test/pleroma/web/web_finger/web_finger_controller_test.exs b/test/pleroma/web/web_finger/web_finger_controller_test.exs index 0023f1e81..7059850bd 100644 --- a/test/pleroma/web/web_finger/web_finger_controller_test.exs +++ b/test/pleroma/web/web_finger/web_finger_controller_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.WebFinger.WebFingerControllerTest do @@ -30,14 +30,24 @@ defmodule Pleroma.Web.WebFinger.WebFingerControllerTest do    end    test "Webfinger JRD" do -    user = insert(:user) +    user = +      insert(:user, +        ap_id: "https://hyrule.world/users/zelda", +        also_known_as: ["https://mushroom.kingdom/users/toad"] +      )      response =        build_conn()        |> put_req_header("accept", "application/jrd+json")        |> get("/.well-known/webfinger?resource=acct:#{user.nickname}@localhost") +      |> json_response(200) + +    assert response["subject"] == "acct:#{user.nickname}@localhost" -    assert json_response(response, 200)["subject"] == "acct:#{user.nickname}@localhost" +    assert response["aliases"] == [ +             "https://hyrule.world/users/zelda", +             "https://mushroom.kingdom/users/toad" +           ]    end    test "it returns 404 when user isn't found (JSON)" do @@ -51,14 +61,20 @@ defmodule Pleroma.Web.WebFinger.WebFingerControllerTest do    end    test "Webfinger XML" do -    user = insert(:user) +    user = +      insert(:user, +        ap_id: "https://hyrule.world/users/zelda", +        also_known_as: ["https://mushroom.kingdom/users/toad"] +      )      response =        build_conn()        |> put_req_header("accept", "application/xrd+xml")        |> get("/.well-known/webfinger?resource=acct:#{user.nickname}@localhost") +      |> response(200) -    assert response(response, 200) +    assert response =~ "<Alias>https://hyrule.world/users/zelda</Alias>" +    assert response =~ "<Alias>https://mushroom.kingdom/users/toad</Alias>"    end    test "it returns 404 when user isn't found (XML)" do diff --git a/test/pleroma/web/web_finger_test.exs b/test/pleroma/web/web_finger_test.exs index 96fc0bbaa..2d7b4a40b 100644 --- a/test/pleroma/web/web_finger_test.exs +++ b/test/pleroma/web/web_finger_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.WebFingerTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.Web.WebFinger    import Pleroma.Factory    import Tesla.Mock @@ -45,6 +45,26 @@ defmodule Pleroma.Web.WebFingerTest do        assert {:error, _} = WebFinger.finger("pleroma.social")      end +    test "returns error when there is no content-type header" do +      Tesla.Mock.mock(fn +        %{url: "http://social.heldscal.la/.well-known/host-meta"} -> +          {:ok, +           %Tesla.Env{ +             status: 200, +             body: File.read!("test/fixtures/tesla_mock/social.heldscal.la_host_meta") +           }} + +        %{ +          url: +            "https://social.heldscal.la/.well-known/webfinger?resource=acct:invalid_content@social.heldscal.la" +        } -> +          {:ok, %Tesla.Env{status: 200, body: ""}} +      end) + +      user = "invalid_content@social.heldscal.la" +      assert {:error, {:content_type, nil}} = WebFinger.finger(user) +    end +      test "returns error when fails parse xml or json" do        user = "invalid_content@social.heldscal.la"        assert {:error, %Jason.DecodeError{}} = WebFinger.finger(user) @@ -56,12 +76,13 @@ defmodule Pleroma.Web.WebFingerTest do        {:ok, _data} = WebFinger.finger(user)      end -    test "returns the ActivityPub actor URI for an ActivityPub user with the ld+json mimetype" do +    test "returns the ActivityPub actor URI and subscribe address for an ActivityPub user with the ld+json mimetype" do        user = "kaniini@gerzilla.de"        {:ok, data} = WebFinger.finger(user)        assert data["ap_id"] == "https://gerzilla.de/channel/kaniini" +      assert data["subscribe_address"] == "https://gerzilla.de/follow?f=&url={uri}"      end      test "it work for AP-only user" do @@ -112,5 +133,52 @@ defmodule Pleroma.Web.WebFingerTest do        ap_id = "https://" <> to_string(:idna.encode("zetsubou.みんな")) <> "/users/lain"        {:ok, _data} = WebFinger.finger(ap_id)      end + +    test "respects json content-type" do +      Tesla.Mock.mock(fn +        %{ +          url: +            "https://mastodon.social/.well-known/webfinger?resource=acct:emelie@mastodon.social" +        } -> +          {:ok, +           %Tesla.Env{ +             status: 200, +             body: File.read!("test/fixtures/tesla_mock/webfinger_emelie.json"), +             headers: [{"content-type", "application/jrd+json"}] +           }} + +        %{url: "http://mastodon.social/.well-known/host-meta"} -> +          {:ok, +           %Tesla.Env{ +             status: 200, +             body: File.read!("test/fixtures/tesla_mock/mastodon.social_host_meta") +           }} +      end) + +      {:ok, _data} = WebFinger.finger("emelie@mastodon.social") +    end + +    test "respects xml content-type" do +      Tesla.Mock.mock(fn +        %{ +          url: "https://pawoo.net/.well-known/webfinger?resource=acct:pekorino@pawoo.net" +        } -> +          {:ok, +           %Tesla.Env{ +             status: 200, +             body: File.read!("test/fixtures/tesla_mock/https___pawoo.net_users_pekorino.xml"), +             headers: [{"content-type", "application/xrd+xml"}] +           }} + +        %{url: "http://pawoo.net/.well-known/host-meta"} -> +          {:ok, +           %Tesla.Env{ +             status: 200, +             body: File.read!("test/fixtures/tesla_mock/pawoo.net_host_meta") +           }} +      end) + +      {:ok, _data} = WebFinger.finger("pekorino@pawoo.net") +    end    end  end diff --git a/test/pleroma/workers/cron/digest_emails_worker_test.exs b/test/pleroma/workers/cron/digest_emails_worker_test.exs index 65887192e..b3ca6235b 100644 --- a/test/pleroma/workers/cron/digest_emails_worker_test.exs +++ b/test/pleroma/workers/cron/digest_emails_worker_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Workers.Cron.DigestEmailsWorkerTest do @@ -14,7 +14,7 @@ defmodule Pleroma.Workers.Cron.DigestEmailsWorkerTest do    setup do: clear_config([:email_notifications, :digest])    setup do -    Pleroma.Config.put([:email_notifications, :digest], %{ +    clear_config([:email_notifications, :digest], %{        active: true,        inactivity_threshold: 7,        interval: 7 diff --git a/test/pleroma/workers/cron/new_users_digest_worker_test.exs b/test/pleroma/workers/cron/new_users_digest_worker_test.exs index 129534cb1..f9ef265c2 100644 --- a/test/pleroma/workers/cron/new_users_digest_worker_test.exs +++ b/test/pleroma/workers/cron/new_users_digest_worker_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Workers.Cron.NewUsersDigestWorkerTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    import Pleroma.Factory    alias Pleroma.Tests.ObanHelpers @@ -28,7 +28,7 @@ defmodule Pleroma.Workers.Cron.NewUsersDigestWorkerTest do      assert email.html_body =~ user.nickname      assert email.html_body =~ user2.nickname      assert email.html_body =~ "cofe" -    assert email.html_body =~ "#{Pleroma.Web.Endpoint.url()}/static/logo.png" +    assert email.html_body =~ "#{Pleroma.Web.Endpoint.url()}/static/logo.svg"    end    test "it doesn't fail when admin has no email" do diff --git a/test/pleroma/workers/purge_expired_activity_test.exs b/test/pleroma/workers/purge_expired_activity_test.exs index b5938776d..98f30f61f 100644 --- a/test/pleroma/workers/purge_expired_activity_test.exs +++ b/test/pleroma/workers/purge_expired_activity_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Workers.PurgeExpiredActivityTest do diff --git a/test/pleroma/workers/purge_expired_filter_test.exs b/test/pleroma/workers/purge_expired_filter_test.exs new file mode 100644 index 000000000..d10586be9 --- /dev/null +++ b/test/pleroma/workers/purge_expired_filter_test.exs @@ -0,0 +1,30 @@ +defmodule Pleroma.Workers.PurgeExpiredFilterTest do +  use Pleroma.DataCase, async: true +  use Oban.Testing, repo: Repo + +  import Pleroma.Factory + +  test "purges expired filter" do +    %{id: user_id} = insert(:user) + +    {:ok, %{id: id}} = +      Pleroma.Filter.create(%{ +        user_id: user_id, +        phrase: "cofe", +        context: ["home"], +        expires_in: 600 +      }) + +    assert_enqueued( +      worker: Pleroma.Workers.PurgeExpiredFilter, +      args: %{filter_id: id} +    ) + +    assert {:ok, %{id: ^id}} = +             perform_job(Pleroma.Workers.PurgeExpiredFilter, %{ +               filter_id: id +             }) + +    assert Repo.aggregate(Pleroma.Filter, :count, :id) == 0 +  end +end diff --git a/test/pleroma/workers/purge_expired_token_test.exs b/test/pleroma/workers/purge_expired_token_test.exs index fb7708c3f..00cbd40cd 100644 --- a/test/pleroma/workers/purge_expired_token_test.exs +++ b/test/pleroma/workers/purge_expired_token_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Workers.PurgeExpiredTokenTest do diff --git a/test/pleroma/workers/scheduled_activity_worker_test.exs b/test/pleroma/workers/scheduled_activity_worker_test.exs index f3eddf7b1..5558d5b5f 100644 --- a/test/pleroma/workers/scheduled_activity_worker_test.exs +++ b/test/pleroma/workers/scheduled_activity_worker_test.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Workers.ScheduledActivityWorkerTest do @@ -11,10 +11,9 @@ defmodule Pleroma.Workers.ScheduledActivityWorkerTest do    import Pleroma.Factory    import ExUnit.CaptureLog -  setup do: clear_config([ScheduledActivity, :enabled]) +  setup do: clear_config([ScheduledActivity, :enabled], true)    test "creates a status from the scheduled activity" do -    Pleroma.Config.put([ScheduledActivity, :enabled], true)      user = insert(:user)      naive_datetime = @@ -32,18 +31,22 @@ defmodule Pleroma.Workers.ScheduledActivityWorkerTest do          params: %{status: "hi"}        ) -    ScheduledActivityWorker.perform(%Oban.Job{args: %{"activity_id" => scheduled_activity.id}}) +    {:ok, %{id: activity_id}} = +      ScheduledActivityWorker.perform(%Oban.Job{args: %{"activity_id" => scheduled_activity.id}})      refute Repo.get(ScheduledActivity, scheduled_activity.id) -    activity = Repo.all(Pleroma.Activity) |> Enum.find(&(&1.actor == user.ap_id)) -    assert Pleroma.Object.normalize(activity).data["content"] == "hi" -  end -  test "adds log message if ScheduledActivity isn't find" do -    Pleroma.Config.put([ScheduledActivity, :enabled], true) +    object = +      Pleroma.Activity +      |> Repo.get(activity_id) +      |> Pleroma.Object.normalize() + +    assert object.data["content"] == "hi" +  end +  test "error message for non-existent scheduled activity" do      assert capture_log([level: :error], fn ->               ScheduledActivityWorker.perform(%Oban.Job{args: %{"activity_id" => 42}}) -           end) =~ "Couldn't find scheduled activity" +           end) =~ "Couldn't find scheduled activity: 42"    end  end diff --git a/test/pleroma/xml_builder_test.exs b/test/pleroma/xml_builder_test.exs index 059384c34..9aae32cdc 100644 --- a/test/pleroma/xml_builder_test.exs +++ b/test/pleroma/xml_builder_test.exs @@ -1,9 +1,9 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.XmlBuilderTest do -  use Pleroma.DataCase +  use Pleroma.DataCase, async: true    alias Pleroma.XmlBuilder    test "Build a basic xml string from a tuple" do diff --git a/test/support/api_spec_helpers.ex b/test/support/api_spec_helpers.ex index 46388f92c..36d6a8b81 100644 --- a/test/support/api_spec_helpers.ex +++ b/test/support/api_spec_helpers.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Tests.ApiSpecHelpers do diff --git a/test/support/builders/user_builder.ex b/test/support/builders/user_builder.ex index 0c687c029..6bccbb35a 100644 --- a/test/support/builders/user_builder.ex +++ b/test/support/builders/user_builder.ex @@ -7,7 +7,7 @@ defmodule Pleroma.Builders.UserBuilder do        email: "test@example.org",        name: "Test Name",        nickname: "testname", -      password_hash: Pbkdf2.hash_pwd_salt("test"), +      password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("test"),        bio: "A tester.",        ap_id: "some id",        last_digest_emailed_at: NaiveDateTime.truncate(NaiveDateTime.utc_now(), :second), diff --git a/test/support/cachex_proxy.ex b/test/support/cachex_proxy.ex new file mode 100644 index 000000000..de1f1c766 --- /dev/null +++ b/test/support/cachex_proxy.ex @@ -0,0 +1,40 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.CachexProxy do +  @behaviour Pleroma.Caching + +  @impl true +  defdelegate get!(cache, key), to: Cachex + +  @impl true +  defdelegate stream!(cache, key), to: Cachex + +  @impl true +  defdelegate put(cache, key, value, options), to: Cachex + +  @impl true +  defdelegate put(cache, key, value), to: Cachex + +  @impl true +  defdelegate get_and_update(cache, key, func), to: Cachex + +  @impl true +  defdelegate get(cache, key), to: Cachex + +  @impl true +  defdelegate fetch!(cache, key, func), to: Cachex + +  @impl true +  defdelegate expire_at(cache, str, num), to: Cachex + +  @impl true +  defdelegate exists?(cache, key), to: Cachex + +  @impl true +  defdelegate del(cache, key), to: Cachex + +  @impl true +  defdelegate execute!(cache, func), to: Cachex +end diff --git a/test/support/captcha/mock.ex b/test/support/captcha/mock.ex index 2ed2ba3b4..175ade131 100644 --- a/test/support/captcha/mock.ex +++ b/test/support/captcha/mock.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Captcha.Mock do diff --git a/test/support/channel_case.ex b/test/support/channel_case.ex index 114184a9f..1fbf6f100 100644 --- a/test/support/channel_case.ex +++ b/test/support/channel_case.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ChannelCase do @@ -30,13 +30,5 @@ defmodule Pleroma.Web.ChannelCase do      end    end -  setup tags do -    :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo) - -    unless tags[:async] do -      Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()}) -    end - -    :ok -  end +  setup tags, do: Pleroma.DataCase.setup_multi_process_mode(tags)  end diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 47cb65a80..deee98599 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Web.ConnCase do @@ -19,6 +19,8 @@ defmodule Pleroma.Web.ConnCase do    use ExUnit.CaseTemplate +  alias Pleroma.DataCase +    using do      quote do        # Import conveniences for testing with connections @@ -65,13 +67,11 @@ defmodule Pleroma.Web.ConnCase do        end        defp json_response_and_validate_schema( -             %{ -               private: %{ -                 open_api_spex: %{operation_id: op_id, operation_lookup: lookup, spec: spec} -               } -             } = conn, +             %{private: %{operation_id: op_id}} = conn,               status             ) do +        {spec, lookup} = OpenApiSpex.Plug.PutApiSpec.get_spec_and_operation_lookup(conn) +          content_type =            conn            |> Plug.Conn.get_resp_header("content-type") @@ -116,21 +116,11 @@ defmodule Pleroma.Web.ConnCase do    end    setup tags do -    Cachex.clear(:user_cache) -    Cachex.clear(:object_cache) -    :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo) +    DataCase.setup_multi_process_mode(tags) +    DataCase.setup_streamer(tags) +    DataCase.stub_pipeline() -    unless tags[:async] do -      Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()}) -    end - -    if tags[:needs_streamer] do -      start_supervised(%{ -        id: Pleroma.Web.Streamer.registry(), -        start: -          {Registry, :start_link, [[keys: :duplicate, name: Pleroma.Web.Streamer.registry()]]} -      }) -    end +    Mox.verify_on_exit!()      {:ok, conn: Phoenix.ConnTest.build_conn()}    end diff --git a/test/support/data_case.ex b/test/support/data_case.ex index d5456521c..0ee2aa4a2 100644 --- a/test/support/data_case.ex +++ b/test/support/data_case.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.DataCase do @@ -18,6 +18,8 @@ defmodule Pleroma.DataCase do    use ExUnit.CaseTemplate +  import Pleroma.Tests.Helpers, only: [clear_config: 2] +    using do      quote do        alias Pleroma.Repo @@ -45,15 +47,41 @@ defmodule Pleroma.DataCase do      end    end -  setup tags do -    Cachex.clear(:user_cache) -    Cachex.clear(:object_cache) +  def clear_cachex do +    Pleroma.Supervisor +    |> Supervisor.which_children() +    |> Enum.each(fn +      {name, _, _, [Cachex]} -> +        name +        |> to_string +        |> String.trim_leading("cachex_") +        |> Kernel.<>("_cache") +        |> String.to_existing_atom() +        |> Cachex.clear() + +      _ -> +        nil +    end) +  end + +  def setup_multi_process_mode(tags) do      :ok = Ecto.Adapters.SQL.Sandbox.checkout(Pleroma.Repo) -    unless tags[:async] do +    if tags[:async] do +      Mox.stub_with(Pleroma.CachexMock, Pleroma.NullCache) +      Mox.set_mox_private() +    else        Ecto.Adapters.SQL.Sandbox.mode(Pleroma.Repo, {:shared, self()}) + +      Mox.set_mox_global() +      Mox.stub_with(Pleroma.CachexMock, Pleroma.CachexProxy) +      clear_cachex()      end +    :ok +  end + +  def setup_streamer(tags) do      if tags[:needs_streamer] do        start_supervised(%{          id: Pleroma.Web.Streamer.registry(), @@ -65,18 +93,35 @@ defmodule Pleroma.DataCase do      :ok    end -  def ensure_local_uploader(context) do -    test_uploader = Map.get(context, :uploader, Pleroma.Uploaders.Local) -    uploader = Pleroma.Config.get([Pleroma.Upload, :uploader]) -    filters = Pleroma.Config.get([Pleroma.Upload, :filters]) +  setup tags do +    setup_multi_process_mode(tags) +    setup_streamer(tags) +    stub_pipeline() -    Pleroma.Config.put([Pleroma.Upload, :uploader], test_uploader) -    Pleroma.Config.put([Pleroma.Upload, :filters], []) +    Mox.verify_on_exit!() -    on_exit(fn -> -      Pleroma.Config.put([Pleroma.Upload, :uploader], uploader) -      Pleroma.Config.put([Pleroma.Upload, :filters], filters) -    end) +    :ok +  end + +  def stub_pipeline do +    Mox.stub_with(Pleroma.Web.ActivityPub.SideEffectsMock, Pleroma.Web.ActivityPub.SideEffects) + +    Mox.stub_with( +      Pleroma.Web.ActivityPub.ObjectValidatorMock, +      Pleroma.Web.ActivityPub.ObjectValidator +    ) + +    Mox.stub_with(Pleroma.Web.ActivityPub.MRFMock, Pleroma.Web.ActivityPub.MRF) +    Mox.stub_with(Pleroma.Web.ActivityPub.ActivityPubMock, Pleroma.Web.ActivityPub.ActivityPub) +    Mox.stub_with(Pleroma.Web.FederatorMock, Pleroma.Web.Federator) +    Mox.stub_with(Pleroma.ConfigMock, Pleroma.Config) +  end + +  def ensure_local_uploader(context) do +    test_uploader = Map.get(context, :uploader) || Pleroma.Uploaders.Local + +    clear_config([Pleroma.Upload, :uploader], test_uploader) +    clear_config([Pleroma.Upload, :filters], [])      :ok    end diff --git a/test/support/factory.ex b/test/support/factory.ex index 8eb07dc3c..5c4e65c81 100644 --- a/test/support/factory.ex +++ b/test/support/factory.ex @@ -1,9 +1,12 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Factory do    use ExMachina.Ecto, repo: Pleroma.Repo + +  require Pleroma.Constants +    alias Pleroma.Object    alias Pleroma.User @@ -29,7 +32,7 @@ defmodule Pleroma.Factory do        name: sequence(:name, &"Test テスト User #{&1}"),        email: sequence(:email, &"user#{&1}@example.com"),        nickname: sequence(:nickname, &"nick#{&1}"), -      password_hash: Pbkdf2.hash_pwd_salt("test"), +      password_hash: Pleroma.Password.Pbkdf2.hash_pwd_salt("test"),        bio: sequence(:bio, &"Tester Number #{&1}"),        is_discoverable: true,        last_digest_emailed_at: NaiveDateTime.utc_now(), @@ -41,23 +44,27 @@ defmodule Pleroma.Factory do      urls =        if attrs[:local] == false do -        base_domain = Enum.random(["domain1.com", "domain2.com", "domain3.com"]) +        base_domain = attrs[:domain] || Enum.random(["domain1.com", "domain2.com", "domain3.com"])          ap_id = "https://#{base_domain}/users/#{user.nickname}"          %{            ap_id: ap_id,            follower_address: ap_id <> "/followers", -          following_address: ap_id <> "/following" +          following_address: ap_id <> "/following", +          featured_address: ap_id <> "/collections/featured"          }        else          %{            ap_id: User.ap_id(user),            follower_address: User.ap_followers(user), -          following_address: User.ap_following(user) +          following_address: User.ap_following(user), +          featured_address: User.ap_featured_collection(user)          }        end +    attrs = Map.delete(attrs, :domain) +      user      |> Map.put(:raw_bio, user.bio)      |> Map.merge(urls) @@ -104,6 +111,37 @@ defmodule Pleroma.Factory do      }    end +  def attachment_note_factory(attrs \\ %{}) do +    user = attrs[:user] || insert(:user) +    {length, attrs} = Map.pop(attrs, :length, 1) + +    data = %{ +      "attachment" => +        Stream.repeatedly(fn -> attachment_data(user.ap_id, attrs[:href]) end) +        |> Enum.take(length) +    } + +    build(:note, Map.put(attrs, :data, data)) +  end + +  defp attachment_data(ap_id, href) do +    href = href || sequence(:href, &"#{Pleroma.Web.Endpoint.url()}/media/#{&1}.jpg") + +    %{ +      "url" => [ +        %{ +          "href" => href, +          "type" => "Link", +          "mediaType" => "image/jpeg" +        } +      ], +      "name" => "some name", +      "type" => "Document", +      "actor" => ap_id, +      "mediaType" => "image/jpeg" +    } +  end +    def audio_factory(attrs \\ %{}) do      text = sequence(:text, &"lain radio episode #{&1}") @@ -190,6 +228,45 @@ defmodule Pleroma.Factory do      }    end +  def add_activity_factory(attrs \\ %{}) do +    featured_collection_activity(attrs, "Add") +  end + +  def remove_activity_factor(attrs \\ %{}) do +    featured_collection_activity(attrs, "Remove") +  end + +  defp featured_collection_activity(attrs, type) do +    user = attrs[:user] || insert(:user) +    note = attrs[:note] || insert(:note, user: user) + +    data_attrs = +      attrs +      |> Map.get(:data_attrs, %{}) +      |> Map.put(:type, type) + +    attrs = Map.drop(attrs, [:user, :note, :data_attrs]) + +    data = +      %{ +        "id" => Pleroma.Web.ActivityPub.Utils.generate_activity_id(), +        "target" => user.featured_address, +        "object" => note.data["object"], +        "actor" => note.data["actor"], +        "type" => "Add", +        "to" => [Pleroma.Constants.as_public()], +        "cc" => [user.follower_address] +      } +      |> Map.merge(data_attrs) + +    %Pleroma.Activity{ +      data: data, +      actor: data["actor"], +      recipients: data["to"] +    } +    |> Map.merge(attrs) +  end +    def note_activity_factory(attrs \\ %{}) do      user = attrs[:user] || insert(:user)      note = attrs[:note] || insert(:note, user: user) @@ -259,7 +336,7 @@ defmodule Pleroma.Factory do    def like_activity_factory(attrs \\ %{}) do      note_activity = attrs[:note_activity] || insert(:note_activity) -    object = Object.normalize(note_activity) +    object = Object.normalize(note_activity, fetch: false)      user = insert(:user)      data = @@ -455,7 +532,8 @@ defmodule Pleroma.Factory do      %Pleroma.Filter{        user: build(:user),        filter_id: sequence(:filter_id, & &1), -      phrase: "cofe" +      phrase: "cofe", +      context: ["home"]      }    end  end diff --git a/test/support/helpers.ex b/test/support/helpers.ex index 224034521..856a6a376 100644 --- a/test/support/helpers.ex +++ b/test/support/helpers.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Tests.Helpers do @@ -8,6 +8,8 @@ defmodule Pleroma.Tests.Helpers do    """    alias Pleroma.Config +  require Logger +    defmacro clear_config(config_path) do      quote do        clear_config(unquote(config_path)) do @@ -18,6 +20,7 @@ defmodule Pleroma.Tests.Helpers do    defmacro clear_config(config_path, do: yield) do      quote do        initial_setting = Config.fetch(unquote(config_path)) +        unquote(yield)        on_exit(fn -> @@ -35,6 +38,15 @@ defmodule Pleroma.Tests.Helpers do    end    defmacro clear_config(config_path, temp_setting) do +    # NOTE: `clear_config([section, key], value)` != `clear_config([section], key: value)` (!) +    # Displaying a warning to prevent unintentional clearing of all but one keys in section +    if Keyword.keyword?(temp_setting) and length(temp_setting) == 1 do +      Logger.warn( +        "Please change to `clear_config([section]); clear_config([section, key], value)`: " <> +          "#{inspect(config_path)}, #{inspect(temp_setting)}" +      ) +    end +      quote do        clear_config(unquote(config_path)) do          Config.put(unquote(config_path), unquote(temp_setting)) @@ -55,6 +67,14 @@ defmodule Pleroma.Tests.Helpers do            clear_config: 2          ] +      def time_travel(entity, seconds) do +        new_time = NaiveDateTime.add(entity.inserted_at, seconds) + +        entity +        |> Ecto.Changeset.change(%{inserted_at: new_time, updated_at: new_time}) +        |> Pleroma.Repo.update() +      end +        def to_datetime(%NaiveDateTime{} = naive_datetime) do          naive_datetime          |> DateTime.from_naive!("Etc/UTC") diff --git a/test/support/http_request_mock.ex b/test/support/http_request_mock.ex index 93464ebff..8807c2d14 100644 --- a/test/support/http_request_mock.ex +++ b/test/support/http_request_mock.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule HttpRequestMock do @@ -89,6 +89,18 @@ defmodule HttpRequestMock do       }}    end +  def get("https://mastodon.sdf.org/users/rinpatch/collections/featured", _, _, _) do +    {:ok, +     %Tesla.Env{ +       status: 200, +       body: +         File.read!("test/fixtures/users_mock/masto_featured.json") +         |> String.replace("{{domain}}", "mastodon.sdf.org") +         |> String.replace("{{nickname}}", "rinpatch"), +       headers: [{"content-type", "application/activity+json"}] +     }} +  end +    def get("https://patch.cx/objects/tesla_mock/poll_attachment", _, _, _) do      {:ok,       %Tesla.Env{ @@ -122,7 +134,7 @@ defmodule HttpRequestMock do       %Tesla.Env{         status: 200,         body: File.read!("test/fixtures/tesla_mock/mike@osada.macgirvin.com.json"), -       headers: activitypub_object_headers() +       headers: [{"content-type", "application/jrd+json"}]       }}    end @@ -187,7 +199,8 @@ defmodule HttpRequestMock do      {:ok,       %Tesla.Env{         status: 200, -       body: File.read!("test/fixtures/tesla_mock/lain_squeet.me_webfinger.xml") +       body: File.read!("test/fixtures/tesla_mock/lain_squeet.me_webfinger.xml"), +       headers: [{"content-type", "application/xrd+xml"}]       }}    end @@ -275,6 +288,15 @@ defmodule HttpRequestMock do       }}    end +  def get("https://peertube.stream/accounts/createurs", _, _, _) do +    {:ok, +     %Tesla.Env{ +       status: 200, +       body: File.read!("test/fixtures/peertube/actor-person.json"), +       headers: activitypub_object_headers() +     }} +  end +    def get("https://peertube.moe/videos/watch/df5f464b-be8d-46fb-ad81-2d4c2d1630e3", _, _, _) do      {:ok,       %Tesla.Env{ @@ -517,22 +539,6 @@ defmodule HttpRequestMock do       }}    end -  def get("http://zetsubou.xn--q9jyb4c/.well-known/host-meta", _, _, _) do -    {:ok, -     %Tesla.Env{ -       status: 200, -       body: File.read!("test/fixtures/tesla_mock/xn--q9jyb4c_host_meta") -     }} -  end - -  def get("https://zetsubou.xn--q9jyb4c/.well-known/host-meta", _, _, _) do -    {:ok, -     %Tesla.Env{ -       status: 200, -       body: File.read!("test/fixtures/tesla_mock/xn--q9jyb4c_host_meta") -     }} -  end -    def get("http://pleroma.soykaf.com/.well-known/host-meta", _, _, _) do      {:ok,       %Tesla.Env{ @@ -777,7 +783,8 @@ defmodule HttpRequestMock do      {:ok,       %Tesla.Env{         status: 200, -       body: File.read!("test/fixtures/tesla_mock/shp@social.heldscal.la.xml") +       body: File.read!("test/fixtures/tesla_mock/shp@social.heldscal.la.xml"), +       headers: [{"content-type", "application/xrd+xml"}]       }}    end @@ -787,7 +794,7 @@ defmodule HttpRequestMock do          _,          [{"accept", "application/xrd+xml,application/jrd+json"}]        ) do -    {:ok, %Tesla.Env{status: 200, body: ""}} +    {:ok, %Tesla.Env{status: 200, body: "", headers: [{"content-type", "application/jrd+json"}]}}    end    def get("http://framatube.org/.well-known/host-meta", _, _, _) do @@ -807,7 +814,7 @@ defmodule HttpRequestMock do      {:ok,       %Tesla.Env{         status: 200, -       headers: [{"content-type", "application/json"}], +       headers: [{"content-type", "application/jrd+json"}],         body: File.read!("test/fixtures/tesla_mock/framasoft@framatube.org.json")       }}    end @@ -867,7 +874,7 @@ defmodule HttpRequestMock do      {:ok,       %Tesla.Env{         status: 200, -       headers: [{"content-type", "application/json"}], +       headers: [{"content-type", "application/jrd+json"}],         body: File.read!("test/fixtures/tesla_mock/kaniini@gerzilla.de.json")       }}    end @@ -910,6 +917,18 @@ defmodule HttpRequestMock do       }}    end +  def get("https://mastodon.social/users/lambadalambda/collections/featured", _, _, _) do +    {:ok, +     %Tesla.Env{ +       status: 200, +       body: +         File.read!("test/fixtures/users_mock/masto_featured.json") +         |> String.replace("{{domain}}", "mastodon.social") +         |> String.replace("{{nickname}}", "lambadalambda"), +       headers: activitypub_object_headers() +     }} +  end +    def get("https://apfed.club/channel/indio", _, _, _) do      {:ok,       %Tesla.Env{ @@ -1065,7 +1084,8 @@ defmodule HttpRequestMock do      {:ok,       %Tesla.Env{         status: 200, -       body: File.read!("test/fixtures/lain.xml") +       body: File.read!("test/fixtures/lain.xml"), +       headers: [{"content-type", "application/xrd+xml"}]       }}    end @@ -1078,7 +1098,16 @@ defmodule HttpRequestMock do      {:ok,       %Tesla.Env{         status: 200, -       body: File.read!("test/fixtures/lain.xml") +       body: File.read!("test/fixtures/lain.xml"), +       headers: [{"content-type", "application/xrd+xml"}] +     }} +  end + +  def get("http://zetsubou.xn--q9jyb4c/.well-known/host-meta", _, _, _) do +    {:ok, +     %Tesla.Env{ +       status: 200, +       body: File.read!("test/fixtures/host-meta-zetsubou.xn--q9jyb4c.xml")       }}    end @@ -1144,7 +1173,8 @@ defmodule HttpRequestMock do      {:ok,       %Tesla.Env{         status: 200, -       body: File.read!("test/fixtures/tesla_mock/kpherox@mstdn.jp.xml") +       body: File.read!("test/fixtures/tesla_mock/kpherox@mstdn.jp.xml"), +       headers: [{"content-type", "application/xrd+xml"}]       }}    end @@ -1272,6 +1302,15 @@ defmodule HttpRequestMock do       }}    end +  def get("https://patch.cx/objects/a399c28e-c821-4820-bc3e-4afeb044c16f", _, _, _) do +    {:ok, +     %Tesla.Env{ +       status: 200, +       body: File.read!("test/fixtures/tesla_mock/emoji-in-summary.json"), +       headers: activitypub_object_headers() +     }} +  end +    def get(url, query, body, headers) do      {:error,       "Mock response not implemented for GET #{inspect(url)}, #{query}, #{inspect(body)}, #{ diff --git a/test/support/mocks.ex b/test/support/mocks.ex new file mode 100644 index 000000000..fd8f825b3 --- /dev/null +++ b/test/support/mocks.ex @@ -0,0 +1,30 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +Mox.defmock(Pleroma.CachexMock, for: Pleroma.Caching) + +Mox.defmock(Pleroma.Web.ActivityPub.ObjectValidatorMock, +  for: Pleroma.Web.ActivityPub.ObjectValidator.Validating +) + +Mox.defmock(Pleroma.Web.ActivityPub.MRFMock, +  for: Pleroma.Web.ActivityPub.MRF.PipelineFiltering +) + +Mox.defmock(Pleroma.Web.ActivityPub.ActivityPubMock, +  for: [ +    Pleroma.Web.ActivityPub.ActivityPub.Persisting, +    Pleroma.Web.ActivityPub.ActivityPub.Streaming +  ] +) + +Mox.defmock(Pleroma.Web.ActivityPub.SideEffectsMock, +  for: Pleroma.Web.ActivityPub.SideEffects.Handling +) + +Mox.defmock(Pleroma.Web.FederatorMock, for: Pleroma.Web.Federator.Publishing) + +Mox.defmock(Pleroma.ConfigMock, for: Pleroma.Config.Getting) + +Mox.defmock(Pleroma.LoggerMock, for: Pleroma.Logging) diff --git a/test/support/mrf_module_mock.ex b/test/support/mrf_module_mock.ex index 028ea542a..4dfdeb3b4 100644 --- a/test/support/mrf_module_mock.ex +++ b/test/support/mrf_module_mock.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule MRFModuleMock do diff --git a/test/support/null_cache.ex b/test/support/null_cache.ex new file mode 100644 index 000000000..47c10ebb6 --- /dev/null +++ b/test/support/null_cache.ex @@ -0,0 +1,49 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/> +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.NullCache do +  @moduledoc """ +  A module simulating a permanently empty cache. +  """ +  @behaviour Pleroma.Caching + +  @impl true +  def get!(_, _), do: nil + +  @impl true +  def put(_, _, _, _ \\ nil), do: {:ok, true} + +  @impl true +  def stream!(_, _), do: [] + +  @impl true +  def get(_, _), do: {:ok, nil} + +  @impl true +  def fetch!(_, key, func) do +    case func.(key) do +      {_, res} -> res +      res -> res +    end +  end + +  @impl true +  def get_and_update(_, _, func) do +    func.(nil) +  end + +  @impl true +  def expire_at(_, _, _), do: {:ok, true} + +  @impl true +  def exists?(_, _), do: {:ok, false} + +  @impl true +  def execute!(_, func) do +    func.(:nothing) +  end + +  @impl true +  def del(_, _), do: {:ok, true} +end diff --git a/test/support/oban_helpers.ex b/test/support/oban_helpers.ex index 2468f66dc..9b6e5256e 100644 --- a/test/support/oban_helpers.ex +++ b/test/support/oban_helpers.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Tests.ObanHelpers do diff --git a/test/support/websocket_client.ex b/test/support/websocket_client.ex index 8c9d4b2b4..34b955474 100644 --- a/test/support/websocket_client.ex +++ b/test/support/websocket_client.ex @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  defmodule Pleroma.Integration.WebsocketClient do diff --git a/test/test_helper.exs b/test/test_helper.exs index ee880e226..0c9783076 100644 --- a/test/test_helper.exs +++ b/test/test_helper.exs @@ -1,5 +1,5 @@  # Pleroma: A lightweight social networking server -# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/> +# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>  # SPDX-License-Identifier: AGPL-3.0-only  os_exclude = if :os.type() == {:unix, :darwin}, do: [skip_on_mac: true], else: []  | 
